我一直在使用 git diff,它会产生彩色输出。但是,我现在发现我需要对某些东西使用普通的差异,并且由于缺少颜色,它产生了大量难以阅读的输出。如何让 diff 产生可读的彩色输出?理想情况下,同时将其管道化,以便轻松查看大文件。
ter*_*don 34
diff无法输出颜色,您需要另一个程序,例如colordiff。终端中的颜色通过ANSI 转义码打印,默认情况下不解释。要less正确显示颜色,您需要-r,甚至更好的-R开关:
colordiff -- "$file1" "$file2" | less -R
Run Code Online (Sandbox Code Playgroud)
来自man less:
-R or --RAW-CONTROL-CHARS
Like -r, but only ANSI "color" escape sequences are
output in "raw" form. Unlike -r, the screen appearance
is maintained correctly in most cases. ANSI "color"
escape sequences are sequences of the form:
ESC [ ... m
where the "..." is zero or more color specification
characters For the purpose of keeping track of screen
appearance, ANSI color escape sequences are assumed to
not move the cursor. You can make less think that
characters other than "m" can end ANSI color escape
sequences by setting the environment variable LESSAN?
SIENDCHARS to the list of characters which can end a
color escape sequence. And you can make less think
that characters other than the standard ones may appear
between the ESC and the m by setting the environment
variable LESSANSIMIDCHARS to the list of characters
which can appear.
Run Code Online (Sandbox Code Playgroud)
或者,您可以使用morewhich 将默认正确显示颜色。
如果您无法安装外部程序,您应该能够使用更手动的方法获得相同的输出:
diff a b |
perl -lpe 'if(/^</){$_ = "\e[1;31m$_\e[0m"}
elsif(/^>/){$_ = "\e[1;34m$_\e[0m"}'
Run Code Online (Sandbox Code Playgroud)
Ksh*_*rma 20
这里的其他答案可能已经过时。从 coreutils 3.5 开始diff,确实可以生成彩色输出,当标准输出不是控制台时,默认情况下该输出是关闭的。
从手册页:
--color[=WHEN]
为输出着色;WHEN可以是never,always, 或auto(默认)
当标准输出是管道时强制颜色输出diff --color=always -- "$file1" "$file2" | less -R应该有效。
将彩色差异管道化为更少:
diff $file1 $file2 | colordiff | less -r
Run Code Online (Sandbox Code Playgroud)
为了使其更具可读性,将其限制为单个屏幕:
diff -uw $file1 $file2 | colordiff | less -r
Run Code Online (Sandbox Code Playgroud)
并且,如果只有一个屏幕的内容,则导致 less 不显示:
diff -uw $file1 $file2 | tee /dev/stderr | colordiff | less -r -F
Run Code Online (Sandbox Code Playgroud)
如果内容少于一个屏幕,则 -F 会导致 less 立即关闭,到 stderr 的管道是因为当 less 关闭时您会丢失输出 - 通过管道到 stderr,即使 less 不显示,它也会得到输出。
另一种(而且我认为更好)的方法是仅使用 -X 来防止清除屏幕的次数减少:
diff -uw $file1 $file2 | colordiff | less -r -X -F
Run Code Online (Sandbox Code Playgroud)
这对我很有效,但可能特定于 bash。colordiff 不是内置的,但很容易安装。