Colour highlighting output based on regex in shell

后端 未结 8 1927
鱼传尺愫
鱼传尺愫 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条回答
  • 2020-12-02 08:03

    If you want to enable this globally, you'll want a terminal feature, not a process that you pipe output into, because a pipe would be disruptive to some command (two problems are that stdout and stderr would appear out-of-order and buffered, and that some commands just behave differently when outputting to a terminal).

    I don't know of any “conventional” terminal with this feature. It's easily done in Emacs, in a term buffer: configure font-lock-keywords for term-mode.

    However, you should think carefully whether you really want that feature all the time. What if the command has its own colors (e.g. grep --color, ls --color)? Maybe it would be better to define a short alias to a colorizer command and run myCommand 2>&1|c when you want to colorize myCommand's output. You could also alias some specific always-colorize commands.

    Note that the return status of a pipeline is its last command, so if you run myCommand | c, you'll get the status of c, not myCommand. Here's a bash wrapper that avoids this problem, which you can use as w myCommand:

    w () {
      "$@" | c
      return $PIPESTATUS[0]
    }
    
    0 讨论(0)
  • 2020-12-02 08:04

    You could probably enable it for specific commands using aliases and user defined shell functions wihtout too much trouble. If your coloring errors I assume you want to process stderr. Since stderr in unbuffered you would probably want to line buffer it by sending through a fifo.

    0 讨论(0)
  • 2020-12-02 08:13

    You can use programs such as:

    • spc (Supercat)
    • grc (Generic Colouriser)
    • highlight
    • histring
    • pygmentize
    • grep --color

    You can do something like this, but the commands won't see a tty (some will refuse to run or behave differently or do weird things):

    exec > >(histring -fEi error)    # Bash
    
    0 讨论(0)
  • 2020-12-02 08:16

    You could try (maybe needs a bit more escaping):

    BLUE="$(tput setaf 4)"
    BLACK="$(tput sgr0)"
    command | sed "s/^ERROR /${BLUE}ERROR ${BLACK}/g"
    
    0 讨论(0)
  • 2020-12-02 08:16

    Try

    tail -f yourfile.log | egrep --color 'DEBUG|'
    

    where DEBUG is the text you want to highlight.

    0 讨论(0)
  • 2020-12-02 08:24

    You can use the hl command avalaible on github :
    git clone http://github.com/mbornet-hl/hl

    Then :
    myCommand | hl -r '^ERROR.*'

    You can use the $HOME/.hl.cfg configuration file to simplify the command line.
    hl is written in C (source is available). You can use up to 42 differents colors of text.

    0 讨论(0)
提交回复
热议问题