简体   繁体   English

我怎么能在循环中grep?

[英]How can I grep in a loop?

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. 我想grep这个特定目录中的每一行。 What is an easy way to do this? 有什么简单的方法可以做到这一点?

There is no need to loop, you can do use grep with the -f option to get patterns from a file: 没有必要循环,你可以使用带-f选项的grep来从文件中获取模式:

grep -f pattern_file files*

From man grep : man grep

-f FILE, --file=FILE -f FILE, - file = FILE

Obtain patterns from FILE, one per line. 从FILE获取模式,每行一个。 The empty file contains zero patterns, and therefore matches nothing. 空文件包含零模式,因此不匹配任何内容。 (-f is specified by POSIX.) (-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

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. 如果在*之后按Tab键,那么shell会将其扩展为满足条件的文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM