70

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'
Tyilo
  • 5,891
  • 12
  • 47
  • 61
  • 7
    Must use `sed`? `grep`'s `-o` switch looks like a shorter and cleaner way: `echo "atestb" | grep -o 'test'`. – manatwork Jul 16 '12 at 07:54
  • In case you are trying to output only the matching portion BETWEEN two known strings, try `echo "aSomethingYouWantb" | sed -En 's/a(.*)b/\1/p'` – luckman212 Oct 17 '20 at 00:59

1 Answers1

71

You need to match the whole line:

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

or

echo "atestb" | sed 's/.*\(test\).*/\1/'
Thor
  • 16,942
  • 3
  • 52
  • 69
  • 3
    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 04:42
  • 1
    How does this answer the question of "only the string [that matched]". Matching the whole line was not in the question. –  Jan 29 '18 at 15:45
  • 3
    @jww: Did you test the answer? You need to match the whole line because it is a substitution command, i.e. you substitute the whole line with what was matched – Thor Jan 30 '18 at 15:43
  • 1
    I had to use `sed -rn 's/.*(MYPATTERN).*/\1/p'` – Oliver Feb 12 '19 at 21:03
  • @Oliver: That is because of the `-r` which interprets the RE as an ERE. The default is to use BRE. [See this comparison for more detail](https://www.gnu.org/software/sed/manual/html_node/BRE-vs-ERE.html) – Thor Feb 13 '19 at 12:43
  • `echo "atetb" | sed 's/.*\(test\).*/\1/'` returns a non match, because it is substitution and not match – Kjeld Flarup Nov 12 '20 at 08:55
  • @kjeldflarup: it returns `test` as the OP requested – Thor Nov 12 '20 at 17:40