[Novalug] searching for strings that contain regex characters with grep/fgrep and bash

Richard Rognlie rrognlie at gamerz.net
Mon Oct 27 10:39:23 EDT 2008


On Mon, Oct 27, 2008 at 07:28:11AM -0700, Jim Ide wrote:
> The goal: to search a text file for strings that may/will
> contain regular expression characters, but I don't want to
> have to backslash or otherwise escape the characters.
> 
> For example:
> $ cat junk.txt
> here is some [] text
> here is a \ backslash
> here is an * asterisk
> -/path/to/somewhere
> $
> 
> For example:
> 
> $ grep "[]" junk.txt
> grep: Unmatched [ or [^
> 
> Adding -F fixes the problem (so does using 'fgrep' instead of 'grep -F'):
> 
> $ grep -F "[]" junk.txt
> here is some [] text
> $ fgrep "[]" junk.txt
> here is some [] text

Right, fgrep is your friend here.

> But, if I search for -/path, there are problems:
> 
> $ fgrep "-/" junk.txt
> fgrep: invalid option -- /

The trick you need here is '--'  tell grep that there are no more options.
Any remaining parameters are "positional" so "expression" and "file list"

[rrognlie at play ~]$ fgrep -- -/ /tmp/foo
-/path/to/somewhere
But, if I search for -/path, there are problems:
$ fgrep "-/" junk.txt
What about the "-/" string?  Is bash doing something with this?
> And, if I search for *, there are more problems:
> 
> $ fgrep "*" junk.txt
> fgrep: blah: Is a directory

[rrognlie at play ~]$ fgrep '*' /tmp/foo
here is an * asterisk
And, if I search for *, there are more problems:
$ fgrep "*" junk.txt

perhaps it is the '' vs the "" and "globbing"   

[rrognlie at play ~]$ fgrep '\' /tmp/foo
here is a \ backslash


> I understand that bash is interpreting the asterisk character.

> What about the "-/" string?  Is bash doing something with this?
> Is there some way to tell grep and bash to ignore these characters
> WITHOUT backslashing them?
> 
> Thanks for your help.
> 
> 
> 
>       
> _______________________________________________
> Novalug mailing list
> Novalug at calypso.tux.org
> http://calypso.tux.org/cgi-bin/mailman/listinfo/novalug

-- 
 /  \__  | Richard Rognlie / Sendmail Ninja / Gamerz.NET Lackey
 \__/  \ | http://www.gamerz.net/~rrognlie    <rrognlie at gamerz.net>
 /  \__/ | Creator of pbmserv at gamerz.net
 \__/    |                Helping reduce world productivity since 1994



More information about the Novalug mailing list