Linux 如何对目录中的所有文件执行grep操作

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

how perform grep operation on all files in a directory

linuxshellgrep

提问by user2147075

Working with xenserver, and I want to perform a command on each file that is in a directory, grepping some stuff out of the output of the command and appending it in a file.

使用 xenserver,我想对目录中的每个文件执行一个命令,从命令的输出中提取一些内容并将其附加到文件中。

I'm clear on the command I want to use and how to grep out string(s) as needed.

我很清楚我想使用的命令以及如何根据需要 grep 出字符串。

But what I'm not clear on is how do I have it perform this command on each file, going to the next, until no more files are found.

但是我不清楚的是如何让它对每个文件执行此命令,转到下一个,直到找不到更多文件。

回答by Narain

In Linux, I normally use this command to recursively grep for a particular text within a dir

在 Linux 中,我通常使用此命令递归 grep 查找目录中的特定文本

grep -rni "string" *

where,

在哪里,

r = recursive i.e, search subdirectories within the current directory
n = to print the line numbers to stdout
i = case insensitive search

r = 递归,即搜索当前目录中的子目录
n = 将行号打印到标准输出
i = 不区分大小写的搜索

回答by umi

grep $PATTERN *would be sufficient. By default, grep would skip all subdirectories. However, if you want to grep through them, grep -r $PATTERN *is the case.

grep $PATTERN *就足够了。默认情况下,grep 会跳过所有子目录。但是,如果您想遍历它们,grep -r $PATTERN *情况就是如此。

回答by Rob

Use find. Seriously, it is the best way because then you can really see what files it's operating on:

使用查找。说真的,这是最好的方法,因为这样你就可以真正看到它在操作哪些文件:

find . -name "*.sql" -exec grep -H "slow" {} \;

Note, the -H is mac-specific, it shows the filename in the results.

请注意,-H 是特定于 mac 的,它在结果中显示文件名。

回答by bryan

If you want to do multiple commands, you could use:

如果要执行多个命令,可以使用:

for I in `ls *.sql`
do
    grep "foo" $I >> foo.log
    grep "bar" $I >> bar.log
done

回答by Noam Manos

To search in all sub-directories, but only in specific file types, use grep with --include.

要在所有子目录中搜索,但仅在特定文件类型中搜索,请将 grep 与--include.

For example, searching recursively in current directory, for text in *.yml and *.yaml :

例如,在当前目录中递归搜索 *.yml 和 *.yaml 中的文本:

grep "text to search" -r . --include=*.{yml,yaml}