简体   繁体   中英

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. 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:

grep -f pattern_file files*

From 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.)

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 :

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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