I would like to find the files containing specific string under linux. I tried something like but could not succeed:
find . -name *.txt | egrep mystring
Here you are sending the file names (output of the find command
) as input to egrep; you actually want to run egrep on the contents of the files.
Here are a couple of alternatives:
find . -name "*.txt" -exec egrep mystring {} \;
or even better
find . -name "*.txt" -print0 | xargs -0 egrep mystring
Check the find command help to check what the single arguments do.
The first approach will spawn a new process for every file, while the second will pass more than one file as argument to egrep; the -print0 and -0 flags are needed to deal with potentially nasty file names (allowing to separate file names correctly even if a file name contains a space, for example).
try:
find . -name '*.txt' | xargs egrep mystring
There are two problems with your version:
Firstly , *.txt
will first be expanded by the shell, giving you a listing of files in the current directory which end in .txt
, so for instance, if you have the following:
[dsm@localhost:~]$ ls *.txt
test.txt
[dsm@localhost:~]$
your find
command will turn into find . -name test.txt
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 not take filenames from STDIN
. To convert them to arguments you need to use xargs
find . -name *.txt | egrep mystring
That will not work as egrep
will be searching for mystring
within the output generated by find . -name *.txt
find . -name *.txt
which are just the path to *.txt
files.
Instead, you can use xargs
:
find . -name *.txt | xargs egrep mystring
你可以用
find . -iname *.txt -exec egrep mystring \{\} \;
这是一个示例,它将返回所有*.log
文件的文件路径,这些文件的行以ERROR
开头:
find . -name "*.log" -exec egrep -l '^ERROR' {} \;
你可以使用egrep的递归选项
egrep -R "pattern" *.log
If you only want the filenames:
find . -type f -name '*.txt' -exec egrep -l pattern {} \;
If you want filenames and matches:
find . -type f -name '*.txt' -exec egrep pattern {} /dev/null \;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.