Search code examples
bashunixif-statementechoxargs

xargs - if condition and echo {}


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?


Solution

  • 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.