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.
2 Answers
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 && baris shorthand forif (foo) { bar }.)
Perhaps you could grep -o (the -o is important) for the required values instead and use those in your script(?) That way you could use the value in more creative ways or perhaps just wrapped in echo's etc.