当我有一个差异时,我如何给它上色,使它看起来更好?

我想它的命令行,所以请没有GUI解决方案。


当前回答

我建议你试试diff-so-fancy。我在工作中使用它,现在看起来确实很棒。它提供了许多选项,非常容易配置你想要的差异。

你可以通过以下方法安装:

sudo npm install -g diff-so-fancy

或者在Mac上:

brew install diff-so-fancy

然后,你可以像这样突出你的差异:

diff -u file1 file2 | diff-so-fancy

其他回答

下面是另一个解决方案,它调用sed来插入适当的颜色ANSI转义序列,分别以红色、绿色和青色显示+、-和@行。

diff -u old new | sed "s/^-/$(tput setaf 1)&/; s/^+/$(tput setaf 2)&/; s/^@/$(tput setaf 6)&/; s/$/$(tput sgr0)/"

与此问题的其他解决方案不同,此解决方案没有显式地阐明ANSI转义序列。相反,它调用tput setaf和tput sgr0命令来生成ANSI转义序列,分别设置适当的颜色和重置终端属性。

要查看tput setaf的每个参数的可用颜色,使用以下命令:

for i in {0..255}; do tput setaf $i; printf %4d $i; done; tput sgr0; echo

下面是输出的样子:

下面是tput setaf和tput sgr0命令生成适当的ANSI转义序列的证据:

$ tput setaf 1 | xxd -g1
00000000: 1b 5b 33 31 6d                                   .[31m
$ tput setaf 2 | xxd -g1
00000000: 1b 5b 33 32 6d                                   .[32m
$ tput setaf 6 | xxd -g1
00000000: 1b 5b 33 36 6d                                   .[36m
$ tput sgr0 | xxd -g1
00000000: 1b 28 42 1b 5b 6d                                .(B.[m

实际上,似乎还有另一个选择(我最近才注意到,当遇到上面描述的问题时):

git diff --no-index <file1> <file2>
# output to console instead of opening a pager
git --no-pager diff --no-index <file1> <file2>

如果您身边有Git(您可能已经在使用它了),那么您将能够使用它进行比较,即使文件本身不受版本控制。如果默认情况下没有启用,那么在这里启用颜色支持似乎比前面提到的一些变通方法要容易得多。

对我来说,我找到了一些解决方案:这是一个有效的解决方案

@echo off
Title a game for YouTube
explorer "https://thepythoncoding.blogspot.com/2020/11/how-to-echo-with-different-colors-in.html"
SETLOCAL EnableDelayedExpansion
for /F "tokens=1,2 delims=#" %%a in ('"prompt #$H#$E# & echo on & for %%b in (1) do rem"') do (
  set "DEL=%%a"
)
echo say the name of the colors, don't read

call :ColorText 0a "blue"
call :ColorText 0C "green"
call :ColorText 0b "red"
echo(
call :ColorText 19 "yellow"
call :ColorText 2F "black"
call :ColorText 4e "white"

goto :Beginoffile

:ColorText
echo off
<nul set /p ".=%DEL%" > "%~2"
findstr /v /a:%1 /R "^$" "%~2" nul
del "%~2" > nul 2>&1
goto :eof

:Beginoffile

使用Vim:

diff /path/to/a /path/to/b | vim -R -

或者更好的是,VimDiff(或vim -d,打字更短)将并排显示两个、三个或四个文件之间的差异。

例子:

vim -d /path/to/[ab]

vimdiff file1 file2 file3 file4

使用bat命令:

diff file1 file2 | bat -l diff