在 linux 系统上找到所有匹配 'name' 的文件,并用它们搜索 'text'
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3786606/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Find all files matching 'name' on linux system, and search with them for 'text'
提问by siliconpi
I need to find all instances of 'filename.ext' on a linux system and see which ones contain the text 'lookingfor'.
我需要在 Linux 系统上找到“filename.ext”的所有实例,并查看哪些包含文本“lookingfor”。
Is there a set of linux command line operations that would work?
是否有一组可行的 linux 命令行操作?
采纳答案by dogbane
find / -type f -name filename.ext -exec grep -l 'lookingfor' {} +
Using a +
to terminate the command is more efficient than \;
because find
sends a whole batch of files to grep
instead of sending them one by one. This avoids a fork/exec for each single file which is found.
使用+
终止命令比更有效\;
,因为find
将整批文件,以grep
代替送他们一个接一个。这避免了找到的每个单个文件的 fork/exec。
A while ago I did some testing to compare the performance of xargs
vs {} +
vs {} \;
and I found that {} +
was faster. Here are some of my results:
不久前我做了一些测试来比较xargs
vs {} +
vs的性能,{} \;
我发现它{} +
更快。以下是我的一些结果:
time find . -name "*20090430*" -exec touch {} +
real 0m31.98s
user 0m0.06s
sys 0m0.49s
time find . -name "*20090430*" | xargs touch
real 1m8.81s
user 0m0.13s
sys 0m1.07s
time find . -name "*20090430*" -exec touch {} \;
real 1m42.53s
user 0m0.17s
sys 0m2.42s
回答by codaddict
Try:
尝试:
find / -type f -name filename.ext -exec grep -H -n 'lookingfor' {} \;
find
searches recursively starting from the root /
for files named filename.ext
and for every found occurrence it runs grep on the file name searching for lookingfor
and if found prints the line number (-n
) and the file name (-H
).
find
从根开始递归搜索/
命名的文件filename.ext
,对于每个找到的出现,它在搜索的文件名上运行 grep lookingfor
,如果找到,则打印行号 ( -n
) 和文件名 ( -H
)。
回答by digen
A more simple one would be,
一个更简单的方法是,
find / -type f -name filename.ext -print0 | xargs -0 grep 'lookingfor'
-print0 to find & 0 to xargs would mitigate the issue of large number of files in a single directory.
-print0 to find & 0 to xargs 将缓解单个目录中大量文件的问题。
回答by Amareswar
Go to respective directory and type the following command.
转到相应的目录并键入以下命令。
find . -name "*.ext" | xargs grep 'lookingfor'
找 。-name "*.ext" | xargs grep '寻找'
回答by R. Oosterholt
I find the following command the simplest way:
我发现以下命令是最简单的方法:
grep -R --include="filename.ext" lookingfor
or add -i
to search case insensitive:
或添加-i
到不区分大小写的搜索:
grep -i -R --include="filename.ext" lookingfor