Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 518
Jim Avatar asked Aug 16 '13 12:08

Jim


2 Answers

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
like image 147
fedorqui 'SO stop harming' Avatar answered Nov 15 '22 06:11

fedorqui 'SO stop harming'


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.

like image 37
Patryk Avatar answered Nov 15 '22 05:11

Patryk