Grep is my enemy...

Michael Abbott michael at
Wed Oct 4 05:51:05 BST 2006

> I want to filter the patterns on the fly (getting rid of the blank lines), 
> and using the result as the pattern file for grep -f.
> I also want to supply a string for the grep data, not a file.  So my command 
> looks something like this:
>   grep -i -v '^[     ]*$' <pattern_file> | grep -f <stdin> <string>
> Can this be done in one statement?

Yes, two tricks, thus:

 	echo "$STRING" |
 	grep -f <(grep -v '^[[:space]]*$' "$PATTERN_FILE")

The first trick, using echo to deliver your pattern to stdin, is pretty 
standard.  It's rather a shame that it fails if (and only if) $STRING 
matches '^-[neE]+$': if anyone knows a more reliable method, please do 

The second trick, <(...), is peculiar to bash, doesn't work if bash is 
called as sh (ok, this is a Linux point), and certainly doesn't work with 

Actually, you could almost certainly (unless your pattern file is really 
excessively large) get away with:

 	echo "$STRING" |
 	grep -e "$(grep -v '^[[:space]]*$' "$PATTERN_FILE")"

which *does* work with sh.

More information about the Ukfreebsd mailing list