10

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 2

15
  • 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 }.)

6
  • 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, 2011 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, 2011 at 10:45
  • @user: Are you implying there's something wrong with Perl? :) Apr 7, 2011 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, 2011 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?) Apr 12, 2011 at 11:58
3

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.

2
  • 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, 2011 at 15:28
  • This is much easier than sed, and any box that has sed probably has grep also. Aug 27, 2020 at 19:41

You must log in to answer this question.

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