grep -f with a here document

917 views Asked by At

Here documents avoid creation of an intermediate, one-time use file. I was hoping to make use of this when getting the full paths of 20 possible files (without using find -o syntax). I expected the following to work:

find | grep -f <<EOF
Controller.java
Main.java
Config.java
EOF

but I get:

grep: option requires an argument -- f

Am I misunderstanding how here documents work? Or does grep -f not play nicely with file descriptors?

I'm also open to solutions with find that can take a list of -name values, but I don't want to have to type -o 20 times.


Best alternative:

cat <<EOF |  xargs --delimiter '\n' --max-args=1 -I% find -iname "*%*"
Controller.java
Main.java
Config.java
EOF

This is intellectually unsatisfying because you're running find on the entire file hierarchy once for each search pattern which won't scale well for large directory hierarchies.

1

There are 1 answers

1
William Pursell On BEST ANSWER

If you're on a system with /proc (eg linux), try:

#!/bin/sh

find . | grep -f /proc/self/fd/3 3<< EOF
Controller.java
Main.java
Config.java
EOF

Or, if your shell supports process substitution (Bourne Shell does not):

#!/bin/bash

find . | grep -f <( cat << EOF
Controller.java
Main.java
Config.java
EOF
)