Find lines in (multiple) files that contain the given line in an input file

awkfilesgreptext processing

If I have a number of files like the following:

file1:

123
456
789
012

file2:

line1  922
line2  392
line3  456
line5  291
line6  201
...

file3:

line1  111
line2  123
line3  19
line5  542
line6  456
...

What's the best way to get all of the lines in file1 which are contained in a line of both file2 and file3?

In this example, it would be just:

456

Best Answer

grep -of file1 file2|xargs -I {} grep -o "{}" file3

This starts by taking the input of file1 and feeding it in line by line into file2, returning the exact matched text if any. Then the results if any are fed into file3 line by line again returning only matched text.

Related Question