Color regex matches - without dropping misses

后端 未结 7 889
日久生厌
日久生厌 2021-02-07 02:21

When using grep --color=always I can get pretty color highlighting for regex matches.

However, grep only returns lines with at least one match.

7条回答
  •  你的背包
    2021-02-07 02:47

    Here is a script I use to colorize output.

    I think I found the idea/snippet on some kind of blog or bash/sed tutorial - can't find it anymore, it was very long time ago.

    #!/bin/bash
    
    red=$(tput bold;tput setaf 1)            
    green=$(tput setaf 2)                    
    yellow=$(tput bold;tput setaf 3)         
    fawn=$(tput setaf 3)
    blue=$(tput bold;tput setaf 4)           
    purple=$(tput setaf 5)
    pink=$(tput bold;tput setaf 5)           
    cyan=$(tput bold;tput setaf 6)           
    gray=$(tput setaf 7)                     
    white=$(tput bold;tput setaf 7)          
    normal=$(tput sgr0)                      
    
    sep=`echo -e '\001'` # use \001 as a separator instead of '/'
    
    while [ -n "$1" ] ; do
      color=${!1}
      pattern="$2"
      shift 2
    
      rules="$rules;s$sep\($pattern\)$sep$color\1$normal${sep}g"
    done
    
    #stdbuf -o0 -i0 sed -u -e "$rules"
    sed -u -e "$rules"
    

    Usage:

    ./colorize.sh color1 pattern1 color2 pattern2 ...
    

    e.g.

    dmesg | colorize.sh red '.*Hardware Error.*' red 'CPU[0-9]*: Core temperature above threshold' \
    green 'wlan.: authenticated.*' yellow 'wlan.: deauthenticated.*'
    

    Doesn't work well with overlapping patterns, but I've found it very useful anyway.

    HTH

提交回复
热议问题