Bouke Bouke - 4 months ago 6x
Bash Question

Unix: Perform grep command for every line from inputfile and save output to file

I'm trying to write a small unix script to search one file for the line that contain a certain term, found in a different file. I would like to save the output of this command to a new file.

I have a file containing terms (terms.txt) which has a term on each line:


For each of these terms, I want to find the line that contains this term in another file (scores.txt) and append the output of this to a new file (output.txt).

The script I have come up with thus far:

for f in `cat terms.txt`;
grep -i $f scores.txt >> output.txt;

Somehow this does not seem to work properly.
Running just the grep command with the term hard coded does indeed give me the right line I'm searching for:

grep -i "term1" scores.txt

Also, a simple echo does give me the right terms:

for f in `cat terms.txt`; do echo $f; done

However, when I try to repeat this with the $f variable, to repeat the same command for every term in my terms.txt, it does not work.

Could someone help me out on this one?


can you try:

grep -if terms.txt scores.txt > output.txt

basically grep's option f treats the strings in the terms.txt file as patterns to search for in scores.txt

If your terms.txt has CRLF line endings, try this:

grep -if <(tr -d '\r' < terms.txt) scores.txt > output.txt