0

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?

  • 2
    doesn't grep add file prefix when more than one file is given as input? – Sundeep Oct 28 '16 at 10:54
1

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
0

This should work for your situation:

grep -HRnF '<pattern>' . --include "<file_name>"

So to search for the word 'test' in all file ending with .txt use something like:

grep -HRnF 'test' . --include "*.txt"
0

GNU grep has option -o:

-o, --only-matching

Print only the matched (non-empty) parts of a matching line, with each such part on a separate output line.

So this should do what you want

grep -f filename.txt -R -H -o /home/*

Note I've also added -H (-with-filename) to print the filename always.

  • 1
    Ooops, thx, edited. – rudimeier Jan 15 '17 at 22:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.