TransWikia.com

Inverse grep using a pattern file doesn't show non-matches

Super User Asked by That Brazilian Guy on November 4, 2021

I have two nearly identical files, "foo" and "bar".

Each file has thousands of lines, one number each line.

If I sort and then diff both files, this is the result:

$ diff foo bar
5984a5985,5986
> 15676
> 15677
7703,7706d7704
< 17486
< 17487
< 17488
< 17489

However, if I grep -Fvf both files, I get zero "non-matches" in both directions:

$ grep -Fvf foo bar
$ grep -Fvf bar foo
$

Why is that? Shouldn’t I be getting results similar to diff? I’d expect the first command to return me the "first half" of the values on diff, and the second grep command to return me the rest.

Why am I not getting the expected results?

One Answer

For diff, unlike grep -Fvf, the order that lines appear matters. Also, since the -x option was not included in the grep command, lines with mere partial matches are excluded from the output.

Reproducible example

Consider these two files:

$ cat foo
156
174
15676
17486
17487
$ cat bar
15677
15678
156
174
15676

The diff command shows they are different while the grep commands produce no output:

$ diff foo bar
0a1,2
> 15677
> 15678
4,5d5
< 17486
< 17487
$ grep -Fvf foo bar; grep -Fvf bar foo

If we were to add -x to require full-line matches, then grep produces:

$ grep -Fvxf foo bar
15677
15678
$ grep -Fvxf bar foo
17486
17487

Additional suggestion

As abligh suggests in the comments, diff -u produces more context which can make the output easier to understand.

Answered by John1024 on November 4, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP