bash Unix命令在所有文件中搜索文本字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11187248/
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-09-09 22:19:14  来源:igfitidea点击:

Unix command to search for text string in all files

macosbashunixfindgrep

提问by MorganR

How do I get unix to search inside ALL files for a the string "hello"?

如何让 unix 在所有文件中搜索字符串“hello”?

I've tried the following but it doesn't work:

我已经尝试了以下但它不起作用:

sudo grep "hello" | find / -name "*" 2>/dev/null

Does anyone have any other ideas?

有没有人有其他想法?

Thank you.

谢谢你。

回答by Ivaylo Strandjev

Maybe this one?

也许是这个?

sudo cd / && grep -rn "hello" *

EDIT: the 'n' option of course is not needed - it simply displays the line numbers and I find it nice. The 'r' option tells grep to perform recursive search within directories.

编辑:当然不需要 'n' 选项 - 它只是显示行号,我觉得很好。'r' 选项告诉 grep 在目录中执行递归搜索。

回答by sorpigal

Use

grep -r 'pattern' /

If your grepsupports -r, (GNU grepdoes); if not use

如果您grep支持-r,(GNU支持grep);如果不使用

find / -type f -exec grep 'pattern' {} +

If your findsupports -execwith +, otherwise use

如果您的find支持-exec+,否则使用

find / -type f -printf '%p
find / -type f -print0 | xargs -0 grep 'pattern'
' | xargs -0 grep 'pattern'

If your findsupports -printfand your xargssupports -0, or

如果您的find支持-printf和您的xargs支持-0,或

find / -type f | xargs grep 'pattern'

If your findsupports only -print0and your xargssupports -0. In all other cases fall back on

如果您find只支持-print0并且您xargs支持-0. 在所有其他情况下依靠

find . -exec grep -H "hello" {} \;

This is maximally compatible, with the caveat that certain unusual file names will fail to be grepped and crafted file names could pose a security risk.

这是最大程度的兼容,但需要注意的是,某些不寻常的文件名将无法被 grep 并且精心制作的文件名可能会带来安全风险。

Note that you will have to be root in order to be sure of searching all files and that the search will be case-sensitive unless you add -ito grep.

请注意,您必须是 root 用户才能确保搜索所有文件,并且搜索将区分大小写,除非您添加-igrep.

回答by HighKing

This?

这个?

##代码##