Colour highlighting output based on regex in shell

后端 未结 8 1923
鱼传尺愫
鱼传尺愫 2020-12-02 07:32

I\'d like to know if I can colour highlight the output of a shell command that matches certain strings.

For example, if I run myCommand, with the output below:

8条回答
  •  Happy的楠姐
    2020-12-02 08:25

    Use awk.

     COLORIZE_AWK_COMMAND='{ print $0 }'
     if [ -n "$COLORIZE" ]; then
         COLORIZE_AWK_COMMAND='
         /pattern1/ { printf "\033[1;30m" }
         /pattern2/ { printf "\033[1;31m" }
         // { print $0 "\033[0m"; }'
     fi
    

    then later you can pipe your output

    ... | awk "$COLORIZE_AWK_COMMAND"
    

    printf is used in the patterns so we don't print a newline, just set the color.

提交回复
热议问题