sed: print only matching group

mort picture mort · Jul 7, 2013 · Viewed 232.7k times · Source

I want to grab the last two numbers (one int, one float; followed by optional whitespace) and print only them.

Example:

foo bar <foo> bla 1 2 3.4

Should print:

2 3.4

So far, I have the following:

sed -n  's/\([0-9][0-9]*[\ \t][0-9.]*[\ \t]*$\)/replacement/p' 

will give me

foo bar <foo> bla 1 replacement

However, if I try to replace it with group 1, the whole line is printed.

sed -n  's/\([0-9][0-9]*[\ \t][0-9.]*[\ \t]*$\)/\1/p' 

How can I print only the section of the line that matches the regex in the group?

Answer

iruvar picture iruvar · Jul 7, 2013

Match the whole line, so add a .* at the beginning of your regex. This causes the entire line to be replaced with the contents of the group

echo "foo bar <foo> bla 1 2 3.4" |
 sed -n  's/.*\([0-9][0-9]*[\ \t][0-9.]*[ \t]*$\)/\1/p'
2 3.4