Print back-reference in regular expression

awkgrepsedshell

I was hoping for a way to make sed replace the entire line with the replacement (rather than just the match) so I could do something like this:

sed -e "/$some_complex_regex_with_a_backref/\1/"

and have it only print the back-reference.

From this question, it seems like the way to do it is mess around with the regex to match the entire line, or use some other tool (like perl). Simply changing the regex to .*regex.* doesn't always work (as mentioned in that question). For example:

$ echo $regex
\([:alpha:]*\)day

$ echo $phrase
it is Saturday tomorrow

$ echo $phrase | sed "s/$regex/\1/"
it is Satur tomorrow

$ echo $phrase | sed "s/.*$regex.*/\1/"

$ # what I'd like to have happen
$ echo $phrase | [[[some command or string of commands]]]
Satur

I'm looking for the most concise way to do this assuming the following:

  • The regex is in a variable, so can't be changed on a case by case basis.
  • I'd like to do this without using perl or other beefier languages.

Best Answer

I don't know sed well enough to answer, but if you are flexible and use grep:

grep --only-matching "complex_regex" file

or

grep -o "complex_regex" file

The --only-matching (or the short form -o) flag tells grep to print out just the matched part, not the whole line.

Related Question