EDIT : I misunderstood the OP and posted the wrong answer. I changed it to an answer that I believe would solve the problem in a more general scenario.
For a file like below:
$ cat input abc 123% 123 abc% this is 456% and nothing more 456
Use sed -n -E 's/(^|.*[^0-9])([0-9]{1,3})%.*/\2/p' input
$ sed -n -E 's/(^|.*[^0-9])([0-9]{1,3})%.*/\2/p' input 123 456
The -n flag allows sed to turn off automatic line output. Then we use the -E flag, which allows us to use extended regular expressions. (In GNU sed, the flag is not -E , but -r instead).
Now comes the command s/// . The group (^|.*[^0-9]) corresponds either to the beginning of a line ( ^ ), or to a sequence of zero or more characters ( .* ) Ending with an insignificant number of char ( [^0-9] ). [0-9]\{1,3\} just matches one to three digits and is tied to a group (using group separators ( and ) ) if the group is preceded by (^|.*[^0-9]) , and then % . Then .* Matches all parameters before and after this pattern. After that, we replace everything with the second group ( ([0-9]{1,3}) ) using the backward link \2 . Since we passed -n to sed, nothing was printed, but we passed the p flag to the s/// command. The result is that if the replacement is performed, the corresponding line is displayed. Note: p is the s/// flag, not the p command, because it appears immediately after the last / .
brandizzi
source share