Sed Only Print Matched Expression

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

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

Robert Thorne
Author

Robert Thorne

Robert Thorne covers electric vehicle innovations, autonomous driving systems, global mobility trends, and automotive engineering developments.