Super User is a question and answer site for computer enthusiasts and power users. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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.

share|improve this question
up vote 5 down vote accepted
  • 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 for if (foo) { bar }.)

share|improve this answer
Ah. The space in the first regexp makes it work like charm. Sadly you still have to match the whole string. I probably going to try awk. – user75250 Apr 6 '11 at 16:25
It looks to me that even awk isn't able to do it. So i have to use full blown perl to match a string and reformat it? – user75250 Apr 7 '11 at 10:45
@user: Are you implying there's something wrong with Perl? :) – grawity Apr 7 '11 at 13:16
This script is used to update the status bar in wmii, so around every second i guess. I dont know whether perl eats to much resources if used just for this purpose of rewritting a string. Guess I have to write my own tool. – user75250 Apr 12 '11 at 10:40
@user: In that case, try bash's [[ $val =~ regex ]], along with $BASH_REMATCH. Also, since it's battery status, consider increasing the interval to 5 or 7 seconds. (By the way, can Linux cache the Perl binary in memory after first exec?) – grawity Apr 12 '11 at 11:58

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.

share|improve this answer
I would prefer to do it with sed (or being told it isn't possible and use awk) in case i want to extend it to do more complicated things with the string. – user75250 Apr 6 '11 at 15:28

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .