如何在忽略前导空白的情况下区分2个文件

我有2个源文件,他们是同一件事的不同版本。然而,一个已经通过一个不同的编辑器进行缩进更改,所以所有的行显示不同的差异。

是否有一个 diff 命令或者一个过滤器可以用来进行 diff,以便在忽略前导空格/制表符之后,输出只是不同的行?

90626 次浏览

diff has some options that can be useful to you:

   -E, --ignore-tab-expansion
ignore changes due to tab expansion


-Z, --ignore-trailing-space
ignore white space at line end


-b, --ignore-space-change
ignore changes in the amount of white space


-w, --ignore-all-space
ignore all white space


-B, --ignore-blank-lines
ignore changes whose lines are all blank

So diff -w old new should ignore all spaces and thus report only substantially different lines.

If one is using tabs incorrectly, you can fix that

expand bad_file
diff -bB file[12]
-b, --ignore-space-change
ignore changes in the amount of white space
-B, --ignore-blank-lines
ignore changes whose lines are all blank

Please note that -w option will ignoring all whitespaces before diffing, so a line like this i s a line and this is a line in each file will compare as thisisaline and will not report differences.

Beside of -w option problem, even -b option has minor issues and that doesn't ignore whitespaces if come at the begging of a line

So you should use sed to remove those whitespaces occurred at start first then do `diff -bB.

diff -bB <(sed 's/^[ \t]*//' file1) <(sed 's/^[ \t]*//' file2)

My open-source Linux tool 'dif' compares files while ignoring various differences including whitespace.

It has many other options for ignoring comments or timestamps, sorting the input files, doing search/replace, ignoring certain lines, etc.

After preprocessing the input files, it runs the Linux tools meld, gvimdiff, tkdiff, or kompare on these intermediate files.

Installation is not required, just download and run the 'dif' executable from https://github.com/koknat/dif

To condense any whitespace to a single space, use the -white option:

dif file1 file2 -white

To remove all whitespace (except for newlines), use the -nowhite option:

dif file1 file2 -nowhite