我有两个看起来与我相同的文件(包括尾随空格和换行符),但 diff 仍然表示它们不同。即使我进行diff -y
并排比较,线条看起来也完全相同。diff 的输出是整个 2 个文件。
知道是什么原因造成的吗?
小智 21
尝试:
diff file1 file2 | cat -t
Run Code Online (Sandbox Code Playgroud)
该-t
选项将导致cat
清楚地显示任何特殊字符 - 例如。^M
对于 CR,^I
对于选项卡。
从手册页(OS X):
Run Code Online (Sandbox Code Playgroud)-t Display non-printing characters (see the -v option), and display tab characters as `^I'. -v Display non-printing characters so they are visible. Control characters print as `^X' for control-X; the delete character (octal 0177) prints as `^?'. Non-ASCII characters (with the high bit set) are printed as `M-' (for meta) followed by the character for the low 7 bits.
mrb*_*mrb 18
差异可能是由 DOS 与 UNIX 行尾或类似原因引起的?
如果你hexdump
他们呢?这可能会更明显地显示差异,例如:
hexdump -C file1 > file1.hex
hexdump -C file2 > file2.hex
diff file1.hex file2.hex
Run Code Online (Sandbox Code Playgroud)
我的第一个猜测,结果得到证实,是这些文件使用不同的行尾。这可能是空格的其他一些差异,例如尾随空格的存在(但您通常不会在很多行上看到)或不同的缩进(制表符与空格)。使用以可见形式打印出空白和控制字符的命令,例如
diff <(cat -A file1) <(cat -A file2)
diff <(sed -n l file1) <(sed -n l file2)
Run Code Online (Sandbox Code Playgroud)
您可以通过首先对它们进行标准化来确认差异仅与行尾有关。你可能有一个dos2unix
实用程序;如果没有,请明确删除额外的 CR (^M, \r, \015) 字符:
diff <(tr -d '\r' <file1) <(tr -d '\r' <file2)
Run Code Online (Sandbox Code Playgroud)
或者,如果file1
是 DOS 结尾的那个
tr -d '\r' <file1 | diff - file2
Run Code Online (Sandbox Code Playgroud)