[ACCEPTED]-how to find files containing a string using egrep-grep
Here you are sending the file names (output 12 of the find command
) as input to egrep; you actually 11 want to run egrep on the contents of the 10 files.
Here are a couple of alternatives:
find . -name "*.txt" -exec egrep mystring {} \;
or 9 even better
find . -name "*.txt" -print0 | xargs -0 egrep mystring
Check the find command help to check what the 8 single arguments do.
The first approach 7 will spawn a new process for every file, while 6 the second will pass more than one file 5 as argument to egrep; the -print0 and -0 4 flags are needed to deal with potentially 3 nasty file names (allowing to separate file 2 names correctly even if a file name contains 1 a space, for example).
try:
find . -name '*.txt' | xargs egrep mystring
There are two problems with your version:
Firstly, *.txt
will 7 first be expanded by the shell, giving you 6 a listing of files in the current directory 5 which end in .txt
, so for instance, if you have 4 the following:
[dsm@localhost:~]$ ls *.txt
test.txt
[dsm@localhost:~]$
your find
command will turn into 3 find . -name test.txt
. Just try the following to illustrate:
[dsm@localhost:~]$ echo find . -name *.txt
find . -name test.txt
[dsm@localhost:~]$
Secondly, egrep
does 2 not take filenames from STDIN
. To convert them 1 to arguments you need to use xargs
find . -name *.txt | egrep mystring
That will not work as egrep
will be searching 3 for mystring
within the output generated by find . -name *.txt
which 2 are just the path to *.txt
files.
Instead, you 1 can use xargs
:
find . -name *.txt | xargs egrep mystring
You could use
find . -iname *.txt -exec egrep mystring \{\} \;
0
Here's an example that will return the file 2 paths of a all *.log
files that have a line that 1 begins with ERROR
:
find . -name "*.log" -exec egrep -l '^ERROR' {} \;
there's a recursive option from egrep you 1 can use
egrep -R "pattern" *.log
If you only want the filenames:
find . -type f -name '*.txt' -exec egrep -l pattern {} \;
If you want 1 filenames and matches:
find . -type f -name '*.txt' -exec egrep pattern {} /dev/null \;
More Related questions
We use cookies to improve the performance of the site. By staying on our site, you agree to the terms of use of cookies.