xargs - if condition and echo {}

Population Xplosive picture Population Xplosive · Feb 28, 2012 · Viewed 22k times · Source

I have some files that contain a particular strings. What I want to do is, search a location for the file; if the file exists grep for the pattern; if true, do something.

find -iname file.xxx| xargs -I {} if grep -Fq "string" {} ; then echo {} ; fi

The problems are:

  • xargs is not working with the if statement.
  • echo {} does not give the file name, instead gives {}.

How do I fix these?

Answer

jcollado picture jcollado · Feb 28, 2012

Try to run the command through a shell like this:

$ find -iname file.xxx |
> xargs -I {} bash -c 'if grep -Fq "string" {} ; then echo {} ; fi'

where the original command has been surrounded by quotes and bash -c.