Friday 21 September 2018

regex - 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.



Answer





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




No comments:

Post a Comment

Where does Skype save my contact's avatars in Linux?

I'm using Skype on Linux. Where can I find images cached by skype of my contact's avatars? Answer I wanted to get those Skype avat...