3

I want to find word abc in a string (I only want the exact word abc, not words that contain abc) but I get the following error:

echo "asjhdhahsjdajhsdabcasjdhas abc asdasdabc" | grep <abc>

bash: syntax error near unexpected token `newline'

6

You want -o (show the matched string only) and -w (match pattern as a whole word only)

$ echo "asjhdhahsjdajhsdabcasjdhas abc asdasdabc" | grep -ow abc
abc

Thanks to steeldriver for explaining how you can actually use the < and > instead of -w to indicate word boundaries. They should be \< and \> but the backslashes have to be quoted to be passed to grep as well as the < symbols, since they also have special meaning to the shell. So strong-quote the expression like this:

echo "asjhdhahsjdajhsdabcasjdhas abc asdasdabc" | grep -o '\<abc\>'

or go crazy with the backslashes:

echo "asjhdhahsjdajhsdabcasjdhas abc asdasdabc" | grep -o \\\<abc\\\>
  • 2
    I think the OP was probably trying to use the \< and \> GNU word boundaries i.e. grep '\<abc\>' (equivalent to your -w flag - or POSIX '\babc\b') – steeldriver Oct 31 '16 at 23:28
  • Thanks, yeah that works. As @steeldriver has mentioned I was trying to use word boundries as it is suggested in here: linuxnix.com/regular-expressions-linux-i – Farhad Nov 1 '16 at 0:43
  • @steeldriver indeed, I was confused by how I don't get any output when I tried escaping them... hmm! – Zanna Nov 1 '16 at 9:03
  • 1
    @Zanna I think it should work if you escape both the backslashes and >,< chars i.e. \\\<abc\\\> – steeldriver Nov 1 '16 at 12:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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