Bash – can I do : find … -exec this && that

bashfind

Is there a way to logically combine two shell commands that are invoked with find – exec?

For instance to print out all the .csv files that contain the string foo together with its occurrence I would like to do:

find . -iname \*.csv -exec grep foo {} && echo {} \;

but bash complains with "missing argument to '-exec' "

Best Answer

-exec is a predicate that runs a command (not a shell) and evaluates to true or false based on the outcome of the command (zero or non-zero exit status).

So:

find . -iname '*.csv' -exec grep foo {} \; -print

would print the file path if grep finds foo in the file. Instead of -print you can use another -exec predicate or any other predicate

find . -iname '*.csv' -exec grep foo {} \; -exec echo {} \;

See also the ! and -o find operators for negation and or.

Alternatively, you can start a shell as:

find . -iname '*.csv' -exec sh -c '
   grep foo "$1" && echo "$1"' sh {} \;

Or to avoid having to start a shell for every file:

find . -iname '*.csv' -exec sh -c '
  for i do
    grep foo "$i" && echo "$i"
  done' sh {} +
Related Question