grep : how to color 2 keywords?
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 ?
Solution 1:
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".
Solution 2:
Try actual regular expressions, rather than piping to another instance of grep
, e.g.:
grep -E "\<foo\>.*\<bar\>" file
This limits to matching lines in which this the keywords match in this order only, unfortunately. Anyway, the use of grep
in your question is rather inefficient and you should avoid it. The answer of @DanielH is pretty much more straightforward for your case, probably.
For an 'or' matching of keywords, I use this regularly:
grep -E "(foo|bar)" file