【问题标题】:How to color shell output in runtime如何在运行时为 shell 输出着色
【发布时间】:2017-07-02 20:00:47
【问题描述】:

当我执行svn up 时,我平均得到约 100 行输出。此外,还有 X-teen 外部组件总共更新约 30 秒(它们每 2-3 秒一个接一个地弹出)。

我想到了对这个输出进行着色(也许是变换),以便我可以更清楚地看到它。

我知道我可以使用sed 来做到这一点,但它需要一个格式讨厌的正则表达式 - 很多转义字符。
另一方面,perl 需要更清晰的正则表达式,但它会在打印输出之前等待整个输入 - 我得到了 30 秒的空白,并且 BAM 整个输出立即出现。

up.sh

#!/bin/bash

svn up $@ \
    | grep -vE "^\s*$|revision" \
    | ${arhbin}/coloring/svn.sh \

${arhbin}/coloring/color_definitions.sh

#!/bin/bash
source ${arhbin}/coloring/color_definitions.sh

cat \
    | perl -pe 's/(^ *A.*$)/'$GREEN'\1'$NORMAL'/igs' \
    | perl -pe 's/(^ *D.*$)/'$RED'\1'$NORMAL'/igs' \
    | perl -pe 's/(^ *C.*$)/'$RED_BG'\1'$NORMAL'/igs' \
    | perl -pe 's/(^ *[?].*$)/'$BLUE'\1'$NORMAL'/igs' \
    | perl -pe 's/(^ *G.*$)/'$BLUE'\1'$NORMAL'/igs' \

如何使用 Perl/Python 之类的正则表达式在运行时为命令的输出着色?

【问题讨论】:

  • 你在 Linux 上吗?
  • 我首先要确保没有缓冲。
  • @hek2mgl 是的,确切地说是红帽
  • @simbabque 我该怎么做?
  • 您应该能够(通过最少的额外研究)将所有替换链接到对perl 的一次调用中。否则这看起来真的很慢。类似 perl 's/(^ *A.*$)/'$GREEN'\1'$NORMAL'/igs;/(^ *D.*$)/'$RED'\1'$NORMAL'/igs;....' 的东西。祝你好运。

标签: regex perl shell sed colors


【解决方案1】:

在 Linux 上,您可以使用 stdbuf 来调整 io 缓冲。像这样:

stdbuf -oL svn up "$@" | perl ... 

【讨论】:

  • 太好了,stdbuf 正是我所需要的,谢谢。这是实际可行的解决方案:svn up $@ | stdbuf -oL grep -vE "^\s*$|revision" (...)
  • 很高兴看到它对您有所帮助!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-12-03
  • 2015-01-30
  • 1970-01-01
  • 2015-05-03
  • 2010-11-29
  • 2011-01-20
  • 1970-01-01
相关资源
最近更新 更多