I want to find some words from a file. I use grep command on linux.

grep "word1" original.file

But there are lots of words to find and they are in "words.file" If it is possible I want to give parameter to grep command. I will give words which are in the "words.file" to the grep command as parameters and find these words in the "original.file"

Can I do that ?

  • how the words in your words.file stored? one per line or with some character separated? If it is one word per line, thiton's solution should work. it would be nice if you put some sample data here. – Kent Sep 22 '11 at 11:05
  • Yes it is one word per line so thiton's solution has worked – user951487 Sep 22 '11 at 12:37
  • then maybe you could choose thiton's solution as answer? I noticed that you 've asked 5 questions so far, and without a single accepted answer? – Kent Sep 22 '11 at 12:59
  • I answered "Was this post useful to you?" question to "Yes" I don't know what else I should do – user951487 Sep 24 '11 at 9:32
  • "When you have decided which answer is the most helpful to you, mark it as the accepted answer by clicking on the check box outline to the left of the answer." stackoverflow.com/faq#howtoask – Burhan Ali Oct 20 '11 at 21:54

man grep helps you: grep has the -f parameter, which specifies that the patterns shall be read from a file.

grep -f words.file original.file

Mind, though, that the words in words.file must be one-per-line, but tr ' ' '\n' helps you with that.



grep -e word1 -e word2 -e word3 original.file

If you want to build the -e word-things from words.file try

eval $(echo -n 'grep '; while read word; do echo -n "-e '$word' "; done < words.file; echo 'original.file')

Perhaps easier and better (but one grep process per word):

xargs -I '{}' grep -e '{}' original.file < words.file
  • 2
    While this is a nice introduction to shell-looping, you might want to know about grep -f :-) – thiton Sep 22 '11 at 10:51

Your Answer

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