Ubuntu – grep : how to color 2 keywords

grep

I know how to grep 2 keywords using 1 command, but I can only manage to color one of them in output . Here is my command:

grep 'keyword1' file.log | grep 'keyword2'

Only keyword2 is highlighted. How can I make keyword1 highlighted at the same time ?

Best Answer

The grep command accepts a --color=always option, so you can use

grep 'keyword1' file.log --color=always | grep 'keyword2'

As gertvdijk points out, this command may be inefficient, but it will look for all lines that contain both keyword1 and keyword2. If you want to highlight them in different colors, you can use

grep 'keyword1' file.log --color=always | GREP_COLORS="mt=01;34" grep --color=always 'keyword2'

which will highlight keyword2 in blue. The mt part means that grep will highlight matching text using this CSI code, and 01;34 means "bold blue foreground on normal background".

Related Question