问题描述:

I have two files. File1 is as follows

Apple

Cat

Bat

File2 is as follows

I have an Apple

Batman returns

This is a test file.

Now I want to check which strings in first file are not present in the second file. I can do a grep -f file1 file2 but thats giving me the matched lines in the second file.

网友答案:

To get the strings that are in the first file and also in the second file:

grep -of file1 file2

The result (using the given example) will be:

Apple
Bat

To get the strings that are in the first file but not in the second file, you could:

grep -of file1 file2 | cat - file1 | sort | uniq -u

Or even simpler (thanks to @triplee's comment):

grep -of file1 file2 | grep -vxFf - file1

The result (using the given example) will be:

Cat

From the grep man page:

-o, --only-matching
Print only the matched (non-empty) parts of a matching line, with each such part on a separate output line.

From the uniq man page:

-u, --unique
Only print unique lines

网友答案:

If you want to show words from file1 that are not in file2, a dirty way is to loop through the words and grep silently. In case of not match, print the word:

while read word
do
    grep -q "$word" f2 || echo "$word"
done < f1

To match exact words, add -w: grep -wq...

Test

$ while read word; do grep -q "$word" f2 || echo "$word"; done < f1
Cat
$ while read word; do grep -wq "$word" f2 || echo "$word"; done < f1
Cat
Bat

A better approach is to use awk:

$ awk 'FNR==NR {a[$1]; next} {for (i=1;i<=NF;i++) {if ($i in a) delete a[$i]}} END {for (i in a) print i}' f1 f2
Cat 
Bat 

This stores the values in file1 into the array a[]. Then, it loops through all lines of file2 checking each single element. If one of them matches a value in the array a[], then this element is removed from the array. Finally, in the END{} block prints the values that were not found.

相关阅读:
Top