Answers:
diff
无法输出颜色,则需要其他程序colordiff
。终端中的颜色是通过ANSI转义码打印的,默认情况下,该转义符会较少地解释。为了less
正确显示颜色,您需要切换-r
,甚至更好-R
:
colordiff -- "$file1" "$file2" | less -R
来自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.
或者,您可以使用more
默认情况下正确显示颜色的。
如果您无法安装外部程序,则应该可以使用更手动的方法获得相同的输出:
diff a b |
perl -lpe 'if(/^</){$_ = "\e[1;31m$_\e[0m"}
elsif(/^>/){$_ = "\e[1;34m$_\e[0m"}'
这里的其他答案可能已过时。从coreutils 3.5开始diff
,确实可以产生彩色输出,当stdout不是控制台时,默认情况下将其关闭。
从手册页:
--color[=WHEN]
着色输出;WHEN
可以是never
,always
或auto
(默认值)
在标准输出为管道时强制输出颜色diff --color=always -- "$file1" "$file2" | less -R
应该起作用。
alias diff='diff --color=always'
在.bashrc
或.zshrc
文件中。
alias diff='diff --side-by-side --left-column --color=always'
alias diff='/usr/bin/diff --color=always '
,alias less='/usr/bin/less -r '
但是虽然diff最初是在少的前几页上着色,但在长的diff上有时会变回单声道。这可能是跳跃,显然不会影响差异,因为它的输出仅生成一次,不必跳跃,但是某种程度上会丢失颜色。
要将有色差异减少到:
diff $file1 $file2 | colordiff | less -r
通过将其限制在单个屏幕上来使其更具可读性:
diff -uw $file1 $file2 | colordiff | less -r
并且,如果只有一个屏幕的内容值得一看,则可以减少不显示的情况:
diff -uw $file1 $file2 | tee /dev/stderr | colordiff | less -r -F
-F导致少于一屏的内容立即关闭,通向stderr的管道是因为当较少关闭时,您将丢失输出-通过管道传递至stderr,即使未显示较少,它也会获得输出。
另一种替代方法(我认为更好)是使用-X来防止较少的清除屏幕:
diff -uw $file1 $file2 | colordiff | less -r -X -F
这对我来说效果很好,但可能特定于bash。colordiff不是内置的,但易于安装。
less -r
less -RM +Gg
:superuser.com/questions/64972/...