Search code examples
bashcolorsgrepansi-escape

Colorize output with different color


I need to colour output using ANSI color for example in blue then we cat a file. But if we grep word error in file this words must be colored red

I try to use grep --colour=always but it reset the coloring to default after word match

For example my console is blue text now, but if i use

cat test.txt | grep -E --color=auto '.*line.*|$'
this is line 2 <<<---this line is red
just doing something <<<- this line is black

Console

And i need console back to blue color

I expect console back to blue color


Solution

  • You can mess with the GREP_COLORS environment variable before running grep.

    GREP_COLORS='sl=36:cx=36' grep -E '.*line.*|$' filename
    

    will color the 'selected line' and 'context line' in the escape color code you set it to (36 being cyan, in this example)

    I will happily give credit to the answer here to use for more reference: https://unix.stackexchange.com/questions/705097/default-value-for-the-grep-colors-environment-variable

    If you still need the terminal colors to be cyan (or whatever color you originally chose) after the grep runs, I'd try just echoing the escape sequence after your call to grep.

    Side note: run your script through shellcheck, cat is redundant with grep. Instead of
    cat filename | grep mystring just use grep mystring filename