109

I have a file A with 100 words in it separated by new lines. I would like to search file B to see if ANY of the words in file A occur in it.

I tried the following but does not work to me:

grep -F A B 
0

3 Answers 3

149

You need to use the option -f:

$ grep -f A B 

The option -F does a fixed string search where as -f is for specifying a file of patterns. You may want both if the file only contains fixed strings and not regexps.

$ grep -Ff A B 

You may also want the -w option for matching whole words only:

$ grep -wFf A B 

Read man grep for a description of all the possible arguments and what they do.

Sign up to request clarification or add additional context in comments.

3 Comments

Is -F just an optimization if you don't want to use regexps?
What about finding all occurrences of words in file A in a directory tree B, listing only the filenames of all matches in B?
@zealoushacker -H to also print the filename.
4

To find a very long list of words in big files, it can be more efficient to use egrep:

# remove the last \n of A $ tr '\n' '|' < A > A_regex $ egrep -f A_regex B 

Comments

0

Use extended regular expression, invoke grep the -E ( or --extended-regexp) option:

grep -E 'pattern1|pattern2' file... 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.