How to find words from one file in another file?

I have 150 words in one text file. I have another text file that contains about 100,000 lines.

How can I check each of the words belonging to the first file, regardless of whether it is in the second or not?

I was thinking about using grep , but I couldn't find out how to use it to read every word in the source text.

Is there a way to do this using awk ? Or another solution?

I tried using this shell script, but it matches almost every line:

 #!/usr/bin/env sh cat words.txt | while read line; do if grep -F "$FILENAME" text.txt then echo "Se encontró $line" fi done 

Another way I found is:

 fgrep -w -o -f "words.txt" "text.txt" 
+8
linux shell grep awk text-manipulation
source share
2 answers

You can use grep -f :

 grep -Ff "first-file" "second-file" 

OR to match the full words:

 grep -w -Ff "first-file" "second-file" 

UPDATE: According to comments:

 awk 'FNR==NR{a[$1]; next} ($1 in a){delete a[$1]; print $1}' file1 file2 
+5
source share

Use grep as follows:

 grep -f firstfile secondfile 

SECOND OPTION

Thanks to Ed Morton for pointing out that the words in the file are “reserved” are treated as patterns. If this is a problem - it may or may not be, the OP may use something like this that does not use patterns:

The file is reserved

 cat dog fox 

and file "text"

 The cat jumped over the lazy fox but didn't land on the moon at all. However it did land on the dog!!! 

Awk script is as follows:

 awk 'BEGIN{i=0}FNR==NR{res[i++]=$1;next}{for(j=0;j<i;j++)if(index($0,res[j]))print $0}' reserved text 

with output:

 The cat jumped over the lazy fox but didn't land on the However it did land on the dog!!! 

THIRD OPTION

Alternatively, this can be done quite simply, but slower in bash:

 while read r; do grep $r secondfile; done < firstfile 
+2
source share

All Articles