I want to get any text that consists of 1 to three digits followed by a % but without the % using sed.
So i guess the following regex should match the right pattern : [0-9]{1,3}%
.
Then i can use this sed command to catch the three digits and only print them : sed -nE 's/.*([0-9]{1,3})%.*/\1/p'
However when i run it, it shows :
$ echo "100%" | sed -nE 's/.*([0-9]{1,3})%.*/\1/p'
0
instead of
100
Obviously, there's something wrong with my sed command and i think the problem comes from here :
[0-9]{1,3}
which apparently doesn't do what i want it to do.
edit:
The .*
at the start of sed -nE 's/.*([0-9]{1,3})%.*/\1/p'
"ate" the two first digits.
The right way to write it, according to Wicktor's answer, is :
sed -nE 's/(.*[^0-9])?([0-9]{1,3})%.*/\2/p'
The .*
grabs all digits leaving just the last of the three digits in 100%
.
Use
sed -nE 's/(.*[^0-9])?([0-9]{1,3})%.*/\2/p'
Details
(.*[^0-9])?
- (Group 1) an optional sequence of any 0 or more chars up to the non-digit char including it([0-9]{1,3})
- (Group 2) one to three digits%
- a %
char.*
- the rest of the string.The match is replaced with Group 2 contents, and that is the only value p
rinted since n
suppresses the default line output.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With