Linux 如何在循环中使用 grep?

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

How can I grep in a loop?

linuxperlbashshellgrep

提问by Jim

I have a file containing text in separate lines.

我有一个包含单独行中的文本的文件。

text1
text2
text3
textN

I have a directory with many files. I want to grep for each line in the of this specific directory. What is an easy way to do this?

我有一个包含许多文件的目录。我想对这个特定目录中的每一行进行 grep。有什么简单的方法可以做到这一点?

采纳答案by fedorqui 'SO stop harming'

There is no need to loop, you can do use grepwith the -foption to get patterns from a file:

无需循环,您可以使用从文件中获取模式grep-f选项:

grep -f pattern_file files*

From man grep:

来自man grep

-f FILE, --file=FILE

Obtain patterns from FILE, one per line. The empty file contains zero patterns, and therefore matches nothing. (-f is specified by POSIX.)

-f 文件,--file=文件

从 FILE 获取模式,每行一个。空文件包含零个模式,因此不匹配任何内容。(-f 由 POSIX 指定。)

Test

测试

$ cat a1
hello
how are you?

$ cat a2
bye
hello

$ cat pattern
hello
bye

$ grep -f pattern a*
a1:hello
a2:bye
a2:hello

回答by Patryk

You can use standard bash loop for this as well :

您也可以为此使用标准的 bash 循环:

for i in text*; do grep "pattern" $i; done

or even better option without loop :

甚至没有循环的更好选择:

grep "pattern" text*

If you press tab after the *then shell will expand it to the files that satisfy the condition.

如果在*then shell之后按 Tab 键会将其扩展为满足条件的文件。