How to make sed only print the matched expression?
I want to rewrite strings like "Battery 0: Charging, 44%, charging" to "Battery: 44%". I tried the following:
sed -n '/\([0-9]*%\)/c Battery: \1'
This doesn't work.
The common "solution" out there is to use search and replace and match the whole line: sed -n 's/.*\([0-9]*%\).*/Battery: \1/p'
Now the .* are too greedy and the \1 is only the %.
Furthermore I don't want to match more than I need to.
Answer
Make the regexp a little more specific.
sed -n 's/.* \([0-9]*%\),.*/Battery: \1/p'
Pick a different tool.
perl -ne '/(\d+%)/ && print "Battery: $1\n";'
(just for the record,
foo && bar
is shorthand forif (foo) { bar }
.)
No comments:
Post a Comment