Wednesday, March 18, 2009

grep using octal patterns and avoid grep: Invalid back reference

Have you ever had a line in a file like this?
This line is fine
This line has  nasty character in it
This line is fine
And then after you read the man page for grep you may have tried this to grep these characters and gotten an error:
$ grep '\240' foo
grep: Invalid back reference
Well, try this instead:
$ grep $'\240' foo
This line has   nasty character in it
Hope that helps.

P.S. Here is a way to use octal dump (od) to figure out the octal value of the nasty character you are trying to match ... in this case it's the "240":
$ grep nasty foo | od -c
0000000 T h i s l i n e h a s 240 n
0000020 a s t y c h a r a c t e r i
0000040 n i t . \n
0000046

1 comment:

MarkO said...

It might be 5 years later, but this did help someone! :) The only straight forward result returned after a bit of Google-searching. Thanks Vernon.