Learn how to use
fgrep to compare the contents of two files with each other. The command can be used to find the contents present in one file but not in the other file. This does not require the file contents to be sorted.
Find contents of file1 that are also present in file2
fgrep -x -f file2 file1
This command takes a line from the file specified next to ‘-f’ and searches for the same in the other file.
-x makes it match the lines exactly(For example, with normal match 123 matches 12345. But with -x, it does not match).
Find the contents of file1 that are not present in file2
fgrep -x -v -f file2 file1
The -v option negates the match.
Examples for fgrep files match
For below examples, let’s assume we have two files with contents as below.
orange apple blue pineapple red watermelon
Now the second file Data2.txt is as below
white red apple green yellow
Find all elements of data1.txt that are also present in data2.txt(In other words, find the records present in both the files)
~# fgrep -x -f data2.txt data1.txt apple red
Find all elements of data1.txt that are NOT present in data2.txt
~# fgrep -v -x -f data1.txt data2.txt white green yellow
‘-x’ helps to match whole line, instead of a partial match. If we remove -x, the output for example 1 would be
fgrep -f data2.txt data1.txt apple pineapple red
fgrep returns the whole file even though only few lines match
This happens if the file specified with -f option has a blank line. Remove blank lines from the file and then fgrep should print only matched lines.
fgrep -v returns empty when there should be some lines not present in the other file
This again happens for the same reason. Verify the first file does not have any blank lines.
Thanks for the examples!