如何将彩色 diff 输出传输到 less?

如何将彩色 diff 输出传输到 less?

我一直在使用 git diff,它会产生彩色输出。然而,我现在发现我需要使用普通的 diff 来完成某些事情,并且它会产生大量由于缺乏颜色而难以阅读的输出。如何使 diff 产生可读的彩色输出?理想情况下,同时将其传输到 less,以便轻松查看大文件。

答案1

diff无法输出颜色,您需要另一个程序,例如colordiff为此。终端中的颜色通过打印ANSI 转义码less 默认情况下不解释。为了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"}'

答案2

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

从手册页:

--color[=WHEN]
对输出进行着色;WHEN可以是never, always, 或auto(默认)

当标准输出是管道时强制颜色输出diff --color=always -- "$file1" "$file2" | less -R应该可以工作。

答案3

将颜色差异通过管道传输到 less:

diff $file1 $file2 | colordiff | less -r

为了使其更具可读性,将其限制为单个屏幕:

diff -uw $file1 $file2 | colordiff | less -r

并且,如果只有一个屏幕的内容,则导致 less 不显示:

diff -uw $file1 $file2 | tee /dev/stderr | colordiff | less -r -F

如果少于一个屏幕的内容,-F 会导致 less 立即关闭,到 stderr 的管道是因为当 less 关闭时,你会丢失输出 - 通过管道到 stderr,即使 less 不显示,它也会获得输出。

另一种(我认为更好)的方法是使用 -X 来防止较少地清除屏幕:

diff -uw $file1 $file2 | colordiff | less -r -X -F

这对我来说效果很好,但可能特定于 bash。 colordiff 不是内置的,但很容易安装。

答案4

我会用即兴演奏:

diff "$A" "$B" | riff

或者只是这个,它将diff在幕后隐式调用:

riff "$A" "$B"

Riff 不仅告诉您哪些行发生了变化,还告诉您线路的哪些部分发生了变化(见下面的截图)。

Riff 默认以与此相同的方式对输出进行分页git,因此您无需担心分页器集成。

最重要的是,Riff 集成了,git因此您也可以从它的朋友那里获得此输出git diff

在这里获取:https://github.com/walles/riff/releases/

即兴演奏

免责声明:我riff自己写的,所以我当然推荐它:)。

相关内容