2

When I run grep -m 1 -Fnxvf file1 file2, for some couple of files I get a different line number than running grep -m 1 -Fnxvf file2 file1 (swapped files).

Why?


I've reduced the files to a minimal example.

file1

Pp: 1        Id pezzo 193        posIn = { x = 132, y = 1432 }
Pp: 1        Id pezzo 193        posIn = { x = 136, y = 1432 }
Pp: 1        Id pezzo 193        posIn = { x = 84, y = 1436 }
Pp: 1        Id pezzo 193        posIn = { x = 88, y = 1436 }

file2

Pp: 1        Id pezzo 193        posIn = { x = 132, y = 1432 }
Pp: 1        Id pezzo 193        posIn = { x = 84, y = 1436 }
Pp: 1        Id pezzo 193        posIn = { x = 88, y = 1436 }
Pp: 1        Id pezzo 193        posIn = { x = 92, y = 1436 }

Results I get:

$ grep -m 1 -Fnaxvf file2 file1
2:Pp: 1      Id pezzo 193        posIn = { x = 136, y = 1432 }
$ grep -m 1 -Fnaxvf file1 file2
4:Pp: 1      Id pezzo 193        posIn = { x = 92, y = 1436 }

The first result is exactly what I'm expecting, but in the second case I expected to see (and usually it is so), the second line of file2.


Long explanation

I'm trying to find (and show) the first difference between two files. I want to show only the first difference, and the line where it happens.

I've found this answer on SO (have a look at my comment to the answer) and it seems to work, but for some couple of files I've noticed the strange behavior showed above.

3

TLDR: you have no guarantee grep will use your pattern in order.

Suppose you have two files with following contents (one letter per line, I fold for readability)

File 1

A B D E

and

File 2

A B C D
  • The first excluded (since you use -v ) letter from set 2 (A B C D ) in file 1 is E.
  • The first excluded letter from set 1 in file 2 is C.

Comparison of files is usually:

  • cmp file1 file2 for binary file, when you don't care about diff (you can even use cmp -s (silent))
  • diff file1 file2 which show a pseudo sed code to go from file1 to file2 (diff file2 file1 is quite symmetric)
  • comm -123 file1 file2 to show lines in common (-3) in file1 (-1) in file2 (-2)
  • Do you know a way I can use cmp, diff or comm to show only the first difference and its line number? – Paolo M Oct 22 '15 at 9:41
  • 2
    output can be limited to X first lines using | head -X – Archemar Oct 22 '15 at 10:32
  • diff can be convinced to show line numbers: diff --unchanged-line-format="" --old-line-format="" --new-line-format="%dn:%L" oldfile newfile | head -1 ought to show the first such line (as it appears in newfile; swap formats for vice-versa) with line number. And now I'm wondering how to combine this with diff -y-like output … – The Sidhekin Oct 22 '15 at 21:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.