使用 printf 启动 scipt 时以不同颜色突出显示特定行

gab*_*ead 5 colors command-line bash

我正在使用 bash 脚本。当我启动脚本时,如何突出显示输出中的特定行?例如,所有带有“启用”的行应为绿色,所有带有“禁用”的行应为红色,所有其他行应为黄色。像这样:

当我运行它时,我使用:

YELLOW="\e[33m"
GREEN="\e[92m"
RED="\e[31m"
printf "${YELLOW}"
./config.sh --enable 1 2 3 4 5 --disable 6 7 8 9
Run Code Online (Sandbox Code Playgroud)

这样,输出是黄色的。没关系,但是如何在启用和禁用线上使用不同的颜色?

输出看起来像:

Enable 1
Enable 2
Enable 3
Enable 4
Enable 5
Disable 6
Disable 7
Disable 8
Disable 9
aaaaaaaaaaa
bbbbbbbbbbb
ccccccccccc
ddddddddddd
Run Code Online (Sandbox Code Playgroud)

然后,在所有启用的行都为绿色并且禁用的行都为红色之后,从aaaaaaaaa开始,之后的所有内容都应为默认的黄色。我怎样才能做到这一点?

Dan*_*l T 6

如果你坚持的话printf可以这样做:

highlight() {
  YELLOW="\e[;33m"
  GREEN="\e[;92m"
  RED="\e[;31m"
  while read -r; do
    case "$REPLY" in
      *Enable*)
        printf "$GREEN%s$YELLOW\n" "$REPLY"
        ;;
      *Disable*)
        printf "$RED%s$YELLOW\n" "$REPLY"
        ;;
      \[????\]*)
        printf "$YELLOW%s\e[m%s\n" "${REPLY:0:6}" "${REPLY:6}"
        ;;
      *)
        printf "$YELLOW%s\n" "$REPLY"
        ;;
    esac
    printf "$YELLOW"
  done
}

# ./config.sh --enable 1 2 3 4 5 --disable 6 7 8 9 |& highlight
highlight < <(setsid ./config.sh --enable 1 2 3 4 5 --disable 6 7 8 9 2>&1 </dev/null)

export CLICOLOR=0
highlight < <(setsid cmake --build ./path/to/build 2>&1 </dev/null)
Run Code Online (Sandbox Code Playgroud)

示例输出

这只是读取每一行并在打印之前添加正确的颜色。|&也捕获 stderr 。@rusty 的答案会更笼统,但它使用 sed 。重置、$YELLOW结束以及脚本setsid中的一些奇怪行为有许多解决方法./config.sh。