Grep – How to Grep Multiple Patterns and Print Results with Match Pattern

grep

I'm looking to grep multiple files with multiple values.
For example: grep -f filename.txt /home/* -R
(filename.txt contains multiple values)

But, I need the know which file contained which value.
For example: /home/blah.txt contains value1, /home/aaa.txt contains value2, etc.

any suggestions?

Best Answer

You can do this using some of the flags provided by grep.

You can try the following command :

grep -R -f filename.txt /home/* will search any pattern inside your filename.txt file and match it recursively against all files inside your home folder. You'll get an output like this :

#here my filename contains the entries bash and Bingo
$grep -R -f filename.txt /home/*
/home/user/.bash_history:vi .bashrc
/home/user/.bash_history:vi .bashrc
/home/user/.bash_history:awk -v RS=END_WORD '/Bingo1/ && /Bingo2/' test2.txt | grep -o 'Pokeman.*'

grep will output the file name and the full line containing your pattern.

If you only want to display the pattern that was found, try the following command :

#here the -o flag only displays the matched values, and -n adds the line number
$grep -R -o -n -f test /home/*
/home/user/.bash_history:128:bash
/home/user/.bash_history:156:bash
/home/user/.bash_history:193:Bingo
Related Question