一般方式的颜色列表

color list in a general way

我认为这可能很容易,但没那么简单

我想根据分隔符为命令的输出着色,在我的例子中

apt-show-versions -u

并希望根据冒号分隔符或单词 'to' 为包的名称着色。 运行 似乎想要解析器而不是过滤器。

在 Linux 和 PuTTY

上使用颜色 xterm

Others have 对类似的功能很感兴趣,我建议你查看那里提到的工具 (grc/grcat)。

尽管如此,您也许可以摆脱 sed-magic。我不确定你到底想给什么上色,我也不知道 apt-show-versions 的输出是什么样的,但这会为冒号和单词 "to":

之前的所有内容上色
cat << EOF | sed -e "s/^[^:]*/\x1b[31m&\x1b[0m/g" | sed -e "s/to/\x1b[31m&\x1b[0m/g"
foo: 1 to 2
bar: 3 to 4
quux: 5 to 6
EOF

您可以将其粘贴到终端中,看看它是否是您要查找的内容。本质上,它搜索正则表达式的出现并用 ANSI 颜色代码将其包围:

  • s/X/Y&Y/g :在整个输入(g 标志)中用 Y 包围替换 X,或者引用 man sed:

    s/regexp/replacement/
           Attempt to match regexp against the pattern space.  If  success‐
           ful,   replace  that  portion  matched  with  replacement.   The
           replacement may contain the special character & to refer to that
           portion  of  the  pattern  space  which matched, and the special
           escapes  through  to refer  to  the  corresponding  matching
           sub-expressions in the regexp.
    
  • ^[^:]* :从行首开始匹配所有内容,直到遇到 :

  • \x1b : 十六进制 27,转义序列 (see here for more!)
  • [31m:红色的 ANSI 颜色代码
  • [0m:"reset to normal output"
  • 的 ANSI 颜色代码

如果有的话,这个 post 告诉我 sed 捕获 & 中的匹配项 ;-) 希望你也有一些见识!