This question already has an answer here:

Say I have two files (file1.txt & file2.txt).

file1.txt: (contains only list of words, one per line)


file2.txt: (contains lines (phrases) using words from file1.txt and more)

he has a Car
there is no food
I have a book
road is straight
Ricky is a good student

The output should be:

he has a Car
Ricky is a good student

marked as duplicate by Scott, thrig, PersianGulf, Eric Renouf, Rahul Aug 16 '16 at 18:21

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

  • 1
    Contrary to common belief, this is not a homework help site. If you have tried to solve the problem at hand but you ran into a problem, please show what you have done and people will help you solve the problem. But do not expect someone to do your work for you. – MelBurslan Aug 16 '16 at 17:12

If your grep supports the -w option:

grep -wFf file1.txt file2.txt

If I'm understanding the question correctly, it sounds like you want to grab lines from file2.txt that contain words from file1.txt

This can easily be achieved by using grep and a for loop.

Basically, you can cat file1.txt and then feed that into a grep command.

for i in $(cat file1.txt); do grep $i file2.txt; done

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