Reputation: 1770
I have a master file which I'm using as a lookup and I have search strings that are phrases.
My current attempt has been
for i in `cat list` #list contains the phrases that I'm looking for
do
grep $i master.file
done
However since my initial search items ($i in this case) is a phrase, I am getting a lot of mismatches. For instance if the phrase is "Blah for the" then I get a lot of matches which have "the" or "for" in them but not the full pattern. From the command line I can do
grep "Blah for the" master.file
which gives me meaningful results. How do I achieve the same results from within the script?
One possible solution is to sed away the spaces in my phrase and also in my master file. But that gets ugly.
Any help appreciated. Thanks!
Upvotes: 2
Views: 170
Reputation: 42067
grep
has the -f
option read newline separated patterns from a file:
grep -f list master.file
Also note that, if you want to search for fixed strings rather than Regex patterns, you also need the -F
option:
grep -Ff list master.file
Upvotes: 3
Reputation: 5177
There are several possibilities. If I understood that correctly, you want to loop over lines not words in your file. Two possible ways are pointed out here: https://unix.stackexchange.com/questions/7011/how-to-loop-over-the-lines-of-a-file
You can either use IFS=$'\n'
to make newlines the only seperator and otherwise use the same code. The other possibility that was pointed out in the linked answer as well is to use read
:
while IFS= read -r i; do
grep "$i" master.file
done < list
Upvotes: 2