Bouke Bouke - 5 months ago 12
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:

term1
term2
term3
term4


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:

#!/bin/bash
for f in `cat terms.txt`;
do
grep -i $f scores.txt >> output.txt;
done


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?

Answer

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
Comments