Sed only print matched expression

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 && bar is shorthand for if (foo) { bar }.)

6

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

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like