Nick Brunt
Nick Brunt

Reputation: 10067

Is it possible to invoke grep with a stored regular expression from a file?

I'm working on a nice long regular expression (for fun, yeah I know...) and I'd like to write it in a file so I can keep a better record of it. Can I call grep like this:

grep regex.txt fileToSearch.txt

I've tried it and it doesn't work. Are there any flags I have to use or is this approach not possible?

Upvotes: 1

Views: 101

Answers (2)

from man grep:

   -f FILE, --file=FILE
          Obtain patterns from FILE, one per line.  The empty file contains zero patterns, and therefore matches nothing.  (-f is specified by POSIX.)

Example:

$> cat ./file.txt 
.*a

$> echo "abcabc" | grep -o -P -f ./file.txt 
abca

Upvotes: 5

sverre
sverre

Reputation: 6919

What about

grep "$(cat regex.txt)" fileToSearch.txt

or

grep --file=regex.txt fileToSearch.txt

Upvotes: 3

Related Questions