Bash terminal output - highlight lines containing

2019-07-18 04:09发布

When I get output in bash I get my standard 2 colour screen. Is there any way I can, by default, highlight a line if it contains some key text output?

E.g. if it contains the word "FAIL" then the line is coloured red.

I’ve read this https://unix.stackexchange.com/questions/46562/how-do-you-colorize-only-some-keywords-for-a-bash-script but am looking for something simpler than having to write a wrapper script which I’d inevitably have to debug at some time in the future.

标签: bash shell
3条回答
混吃等死
2楼-- · 2019-07-18 04:36

Building on tripleee's answer, following command will highlight the matching line red and preserve the other lines:

 your_command | grep --color -e ".*FAIL.*" -e "^"

If you prefer an inverted line:

 your_command | GREP_COLORS='mt=7' grep --color -e ".*FAIL.*" -e "^"
查看更多
叼着烟拽天下
3楼-- · 2019-07-18 04:40

If you're happy to install a BASH script and ack, the hhlighter package has useful default colours and an easy interface https://github.com/paoloantinori/hhighlighter:

hhighlight example

You can use it like so to highlight rows that start with FAIL:

h -i 'FAIL.*'

or that contain FAIL:

h -i '.*FAIL.*'

or for various common log entries:

h -i '.*FAIL.*' '.*PASS.*' '.*WARN.*'
查看更多
forever°为你锁心
4楼-- · 2019-07-18 04:42

For a simple workaround, pipe it through grep --color to turn some words red.

Add a fallback like ^ to print lines which do not contain any matches otherwise.

grep --color -e 'FAIL' -e '^' <<<$'Foo\nBar FAIL Baz\nIck'

Grep output with multiple Colors? describes a hack for getting multiple colors if you need that.

查看更多
登录 后发表回答