sed - Replace numbers from one to several digits
Hello,
I am currently learning how to use sed and want to format a sample output of smartctl. This is the output: Code:
Vendor Specific SMART Attributes with Thresholds: At the moment my command removes just the first digit of every number: Code:
root@localhost:/var/prtg/scriptsxml# smartctl | grep -A25 'Vendor' | sed -n -E 's/(\s*)[0-9](\s*)//p' |
there are several ways to do that:
Code:
sed 's/^....//' # remove the first 4 chars |
Well, first if you want to skip the first line of the output,
Code:
sed -n -E '1d; s/(\s*)[0-9]//p' Code:
smartctl | awk '$1+0<100' Code:
smartctl | sed -n -E '/^[[:space:]]*[0-9]{1,2}[[:space:]]/p' |
My solution is not too different from what the others have posted, except I combined the characters into a character class.
Code:
sed 's/^[[:space:][:digit:]]+//g' |
Quote:
|
To replace from one to several digits, use the + quantifier (or its lazy variant +?) combined with [0-9] (because sed doesn't support \d and [[:digit:]] is unnecessarily verbose).
+ means "as many as possible, at least one" +? means "at least one, as many as required" Contrasted with * which means "as many as possible, none required", and *? which means "as few as possible". The difference between greedy and lazy quantifiers can be subtle - in your example it doesn't matter which is used, but there are other situations where it does matter, so it's a useful thing to keep in mind. Note that sed needs extended mode (-E) for all the above to work except * So, to handle lines starting with optional spaces, then at least one digit, then a space: Code:
sed -E 's/^ *[0-9]+ //' |
Quote:
|
All times are GMT -5. The time now is 01:58 AM. |