vinay rao
vinay rao

Reputation: 49

grep invert match on two files

I have two text files containing one column each, for example -

File_A       File_B

1              1

2              2

3              8

If I do grep -f File_A File_B > File_C, I get File_C containing 1 and 2. I want to know how to use grep -v on two files so that I can get the non-matching values, 3 and 8 in the above example.

Thanks.

Upvotes: 1

Views: 1922

Answers (3)

RomanPerekhrest
RomanPerekhrest

Reputation: 92904

With GNU diff command (to compare files line by line):

diff --suppress-common-lines -y f1 f2 | column -t

The output (left column contain lines from f1, right column - from f2):

3  |  8

-y, --side-by-side - output in two columns

Upvotes: 0

Sundeep
Sundeep

Reputation: 23707

You can also use comm if it allows empty output delimiter

$ # -3 means suppress lines common to both input files
$ # by default, tab character appears before lines from second file
$ comm -3 f1 f2
3
    8
$ # change it to empty string
$ comm -3 --output-delimiter='' f1 f2
3
8

Note: comm requires sorted input, so use comm -3 --output-delimiter='' <(sort f1) <(sort f2) if they are not already sorted


You can also pass common lines got from grep as input to grep -v. Tested with GNU grep, some version might not support all these options

$ grep -Fxf f1 f2 | grep -hxvFf- f1 f2
3
8
  • -F option to match strings literally, not as regex
  • -x option to match whole lines only
  • -h to suppress file name prefix
  • f- to accept stdin instead of file input

Upvotes: 1

P....
P....

Reputation: 18411

awk 'NR==FNR{a[$0]=$0;next} !($0 in a) {print a[(FNR)], $0}' f1 f2
3 8

To Understand the meaning of NR and FNR check below output of their print.

awk '{print NR,FNR}' f1 f2
1 1
2 2
3 3
4 4
5 1
6 2
7 3
8 4

Condition NR==FNR is used to extract the data from first file as both NR and FNR would be same for first file only.

Upvotes: 0

Related Questions