98

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

2 Answers 2

138

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.

3
  • 4
    Is -F just an optimization if you don't want to use regexps?
    – Simd
    Jul 25, 2013 at 18:34
  • What about finding all occurrences of words in file A in a directory tree B, listing only the filenames of all matches in B? Sep 24, 2014 at 5:00
  • @zealoushacker -H to also print the filename. Feb 12, 2022 at 2:12
3

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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