搜索字符串:Find and Grep

人气:296 发布:2022-10-16 标签: command-line grep find

问题描述

必须有更好/更短的方法来做到这一点:

There must be a better / shorter way to do this:

# Find files that contain <string-to-find> in current directory
#   (including sub directories) 
$ find . | xargs grep <string-to-find>

此外,仅搜索例如HTML 文件:

Also, to search only e.g. HTML files:

 # find . | grep html$ | xargs grep <string-to-find>

先谢谢了!

推荐答案

find . -name *.html

或者,如果您想查找名称与正则表达式匹配的文件:

or, if you want to find files with names matching a regular expression:

find . -regex filename-regex.*.html 

或者,如果您想在名称与正则表达式匹配的文件中搜索正则表达式

or, if you want to search for a regular expression in files with names matching a regular expression

find . -regex filename-regex.*.html -exec grep -H string-to-find {} ;

grep 参数-H 输出文件名,如果感兴趣的话.如果没有,您可以安全地删除它并简单地使用 grep.这将指示 find 对其找到的每个文件名执行 grep string-to-find filename,从而避免参数列表过长的可能性,以及需要find 在将结果传递给 xargs 之前完成执行.

The grep argument -H outputs the name of the file, if that's of interest. If not, you can safely remove it and simply use grep. This will instruct find to execute grep string-to-find filename for each file name it finds, thus avoiding the possibility of the list of arguments being too long, and the need for find to finish executing before it can pass its results to xargs.

为了解决你的例子:

find . | xargs grep <string-to-find>

可以替换为

find . -exec grep -H string-to-find {} ;

find . | grep html$ | xargs grep <string-to-find>

可以替换为

find . -name *.html -exec grep -H string-to-find {} ;

798