Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

Possible Duplicate:
Extracting a regex matched with 'sed' without printing the surrounding characters

How do I make this only print test:

echo "atestb" | sed -n 's/\(test\)/\1/p'
share|improve this question

marked as duplicate by Gilles, Mat, Renan, jasonwryan, Stéphane Gimenez Aug 20 '12 at 17:06

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

Must use sed? grep's -o switch looks like a shorter and cleaner way: echo "atestb" | grep -o 'test'. – manatwork Jul 16 '12 at 7:54
I can't use sed because the real thing is like echo 'afoo="test"b' | sed -n 's/.*foo="\([^"]*\)".*/\1/p', where I only want to match test. – Tyilo Jul 16 '12 at 15:53
up vote 20 down vote accepted

You need to match the whole line:

echo "atestb" | sed -n 's/.*\(test\).*/\1/p'


echo "atestb" | sed 's/.*\(test\).*/\1/'
share|improve this answer
I had to add the -r or ` --regexp-extended` option otherwise I was getting invalid reference \1 on s' command's RHS ` error. – Daniel Sokolowski Aug 11 '14 at 16:12
@danielsokolowski: this example uses basic regular expressions (BRE) and thus capture groups are noted with escaped parentheses. If you add -r to the above you should get an error saying "invalid reference". What version of sed are you using? – Thor Aug 11 '14 at 20:46
sed (GNU sed) 4.2.2 on cygwin – Daniel Sokolowski Aug 12 '14 at 4:42

Not the answer you're looking for? Browse other questions tagged or ask your own question.