1つのコマンドを使用して2つのキーワードをgrepする方法を知っていますが、出力でそれらの1つに色を付けることしかできません。これが私のコマンドです:
grep 'keyword1' file.log | grep 'keyword2'
keyword2
のみが強調表示されています。同時にkeyword1
を強調表示するにはどうすればよいですか?
1つのコマンドを使用して2つのキーワードをgrepする方法を知っていますが、出力でそれらの1つに色を付けることしかできません。これが私のコマンドです:
grep 'keyword1' file.log | grep 'keyword2'
keyword2
のみが強調表示されています。同時にkeyword1
を強調表示するにはどうすればよいですか?
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
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".