How can I ignore line endings when comparing files?
Asked Answered
P

1

130

I am comparing two text files and I get the following result:

diff file1 file2 | grep 12345678

> 12345678
< 12345678

As you can see, the same string exists in both files, and both files were sorted with sort.

The line endings must be getting in the way here (Windows vs. Unix).

Is there a way to get diff to ignore line endings on Unix?

Pyrone answered 5/12, 2016 at 12:19 Comment(6)
diff --strip-trailing-cr file1 file2?Miranda
@RuslanOsmanov sounds like an answer, thank you. Btw is that the same as -w ?Pyrone
No, -w ignores differences in white spaces, and "White space" characters include tab, vertical tab, form feed, carriage return, and space. For instance, diff a b will show difference for ` line` and <tab>line, but diff -w a b won'tMiranda
@RuslanOsmanov That's a fine explanation, would you mind to shift it to an answer so I can accept it.Pyrone
Does this answer your question? Line-end agnostic diff?. Nearly 9 years prior.Agincourt
@PeterMortensen not exactly, that question talks about using grep and other unix tools, which would require some inline conversion (for example via sed). This question is purely about using diff, where arguments to diff are the best solution.Pyrone
M
218

Use the --strip-trailing-cr option:

diff --strip-trailing-cr file1 file2

The option causes diff to strip the trailing carriage return character before comparing the files.

Miranda answered 5/12, 2016 at 12:35 Comment(5)
Thanks! I tried using diff -w which gave similar results but this is the most correct answer.Pyrone
This still shows a difference on a change between Allman and 1TBS bracing style.Tarboosh
For some reason I misread this as --skip-trailing-cr instead of --strip-trailing-cr. I hope this comment is helpful to somebody!Judicature
This doesn't work in conjunction with the -y (side-by-side) option. Trailing CR's are not ignored.Tews
@Judicature remember - "strip before you skip" :)Pyrone

© 2022 - 2024 — McMap. All rights reserved.