Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the first percent from a list in bash

Tags:

regex

sed

I have been trying to find a solution all day. I eventually came access a question here that provided two commands. They are:

echo blabla 20% a13724bla-bla244 35% | sed -e 's/[^%0-9 ]*//g;s/  */\n/g' | sed -n '/%/p'
echo blabla 20% a13724bla-bla244 35% | sed 's/.*[ \t][ \t]*\([0-9][0-9]*\)%.*/\1/'

The first is supposed to give all the percentages found in the string and the second should only be used if you are expecting one percentage. My string will have more than one so I have been trying to use the first one. However, it returns all numbers in the strings and n representing spaces.

When I try to use the second command, I get the last percentage in my list which i don't need. I need the first percentage. Any help with this would be greatly appreciated.

like image 680
Christopher Littlewood Avatar asked Dec 09 '25 12:12

Christopher Littlewood


1 Answers

perl would be easier to use as it supports non-greedy quantifier

$ echo 'blabla 20% a13724bla-bla244 35%' | perl -pe 's/.*?(\d+%).*/$1/'
20%
  • .*? minimally match any character
  • (\d+%) the first number followed by % combination
  • .* rest of the line
  • $1 replace the line with text matched within ()
like image 189
Sundeep Avatar answered Dec 12 '25 13:12

Sundeep



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!