如何将有色差异输出减少?


37

我一直在使用git diff,它产生彩色输出。但是,我现在发现我需要对某些东西使用普通的diff,并且由于缺少颜色,它会产生很多难以阅读的输出。如何使diff产生可读的彩色输出?理想情况下,通过管道将其减少到更少,以便于查看大文件。

Answers:


32

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"}'

1
如果有人想查看显示的数据的百分比,他们必须使用less -RM +Ggsuperuser.com/questions/64972/...
baptx

13

这里的其他答案可能已过时。从coreutils 3.5开始diff,确实可以产生彩色输出,当stdout不是控制台时,默认情况下将其关闭。

从手册页:

--color[=WHEN]
着色输出;WHEN可以是neveralwaysauto(默认值)

在标准输出为管道时强制输出颜色diff --color=always -- "$file1" "$file2" | less -R应该起作用。


您也可以将其包含alias diff='diff --color=always'.bashrc.zshrc文件中。
jftuga

1
是。我正在使用alias diff='diff --side-by-side --left-column --color=always'
Kshitiz Sharma

我使用alias diff='/usr/bin/diff --color=always 'alias less='/usr/bin/less -r '但是虽然diff最初是在少的前几页上着色,但在长的diff上有时会变回单声道。这可能是跳跃,显然不会影响差异,因为它的输出仅生成一次,不必跳跃,但是某种程度上会丢失颜色。
NeilG

8

要将有色差异减少到:

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不是内置的,但易于安装。


2
他唯一需要的命令是less -r
sendmoreinfo
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.