"while read LINE do" and grep problems

Kevin picture Kevin · Apr 11, 2011 · Viewed 70.7k times · Source

I have two files.

file1.txt:  
Afghans  
Africans  
Alaskans  
...  

where file2.txt contains the output from a wget on a webpage, so it's a big sloppy mess, but does contain many of the words from the first list.

Bashscript:

cat file1.txt | while read LINE; do grep $LINE file2.txt; done

This did not work as expected. I wondered why, so I echoed out the $LINE variable inside the loop and added a sleep 1, so i could see what was happening:

cat file1.txt | while read LINE; do echo $LINE; sleep 1; grep $LINE file2.txt; done

The output looks in terminal looks something like this:

Afghans
Africans
Alaskans
Albanians
Americans
grep: Chinese: No such file or directory
: No such file or directory
Arabians
Arabs
Arabs/East Indians
: No such file or directory
Argentinans
Armenians
Asian
Asian Indians
: No such file or directory
file2.txt: Asian Naruto
...

So you can see it did finally find the word "Asian". But why does it say:

No such file or directory

?

Is there something weird going on or am I missing something here?

Answer

glenn jackman picture glenn jackman · Apr 11, 2011

What about

grep -f file1.txt file2.txt