By far the safest and easiest way to do this kind of thing is to use find's -exec
option. From man find
:
-exec utility [argument ...] ;
True if the program named utility returns a zero value as its exit status.
Optional arguments may be passed to the utility. The expression must be
terminated by a semicolon (``;''). If you invoke find from a shell you
may need to quote the semicolon if the shell would otherwise treat it as a
control operator. If the string ``{}'' appears anywhere in the utility
name or the arguments it is replaced by the pathname of the current file.
Utility will be executed from the directory from which find was executed.
Utility and arguments are not subject to the further expansion of shell
patterns and constructs.
-exec utility [argument ...] {} +
Same as -exec, except that ``{}'' is replaced with as many pathnames as
possible for each invo-cation invocationcation of utility. This behaviour
is similar to that of xargs(1).
In other words the -exec
option will run whatever you give it on the results of find, replacing {}
with each file (or directory) found. So, to grep for a particular string, you would do:
find src/main -name "*" -exec grep -i 'mystring' {} +
That, however, will also find directories and will give an error. It will work, mind you, it will just complain when you try to run it on a directory, you would have had the same problem using xargs
. What you are actually trying to do here is to find all files and only files. In that case, the -name '*'
is not needed since find src/main
is exactly the same as find src/main -name "*"
. So, instead of using that, specify that you only want to find files:
find src/main -type f -exec grep -i 'mystring' {} +