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 grep for every line in this particular directory. What is an easy way to do this?

+4
source share
2 answers

There is no need for a loop, you can use grep with the -f option to get patterns from a file:

 grep -f pattern_file files* 

From man grep :

-f FILE, --file = FILE

Get patterns from FILE, one per line. An empty file contains zero patterns and therefore nothing matches. (-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 
+11
source

You can also use the standard bash loop for this:

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

or even the best option without a loop:

 grep "pattern" text* 

If you click the tab after * , then the shell expands it to files that satisfy the condition.

+2
source

Source: https://habr.com/ru/post/1497428/


All Articles