在 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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-03 23:37:25  来源:igfitidea点击:

Find all files matching 'name' on linux system, and search with them for 'text'

linuxcommand-linefindgrep

提问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 findsends a whole batch of files to grepinstead 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 xargsvs {} +vs {} \;and I found that {} +was faster. Here are some of my results:

不久前我做了一些测试来比较xargsvs {} +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' {} \;

findsearches recursively starting from the root /for files named filename.extand for every found occurrence it runs grep on the file name searching for lookingforand 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 -ito search case insensitive:

或添加-i到不区分大小写的搜索:

grep -i -R --include="filename.ext" lookingfor