Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 900
Population Xplosive Avatar asked Feb 28 '12 15:02

Population Xplosive


People also ask

How do you pass arguments to xargs?

The -c flag to sh only accepts one argument while xargs is splitting the arguments on whitespace - that's why the double quoting works (one level to make it a single word for the shell, one for xargs).

What does xargs command do?

xargs (short for "extended arguments") is a command on Unix and most Unix-like operating systems used to build and execute commands from standard input. It converts input from standard input into arguments to a command.

What is xargs option?

xargs is a Unix command which can be used to build and execute commands from standard input. Importance : Some commands like grep can accept input as parameters, but some commands accepts arguments, this is place where xargs came into picture. -L max-lines : use at-most max-lines non-blank input lines per command line.

What does xargs n1 do?

xargs reads items from the standard input, delimited by blanks (which can be protected with double or single quotes or a backslash) or newlines, and executes the command (default is echo) one or more times with any initial-arguments followed by items read from standard input.


1 Answers

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.

like image 96
jcollado Avatar answered Sep 17 '22 00:09

jcollado