我该如何使用grep命令来同时显示匹配和不匹配的内容?匹配的内容应该是红色的,其他内容应该是普通颜色。
有没有可用的grep选项可以实现这个功能?
awk
。cat file
one song
two cars
three houses
awk '/two/ {$0="\033[1;31m"$0"\033[0m"}1' file
one song
two cars
three houses
awk '/two/ {$0="\033[1;31m"$0"\033[0m"} /hous/ {$0="\033[1;36m"$0"\033[0m"}1' file
one song
two cars
three houses
tail
结合起来,以不同的颜色显示正在发生的事情。awk '{gsub(/two/,"\033[1;31m&\033[0m")}1' file
查看可用选项:
awk 'BEGIN {for (a=0;a<=1;a++) for (f=30;f<=37;f++) for (b=40;b<=47;b++) print "\033["a";"f";"b"m"a,f,b"\033[m"}'
awk '/two/ {$0="\033[1;31m"$0"\033[0m"}1' file
- Krishna M\033[1;31m
是在 awk
中设置 ANSI 颜色的转义代码。您可以查看此表格,其中 1
表示粗体,31
表示红色前景等等: http://pueblo.sourceforge.net/doc/manual/ansi_color_codes.html - Jotnegrep --color 'pattern\|^' file
如果你想将整行都着色,而不仅仅是匹配的表达式,请修改正则表达式以匹配整个行。
grep --color '.*pattern.*\|^' file
grep -E
,也称为egrep
,来避免使用反斜杠。(我相信也可能存在史前的grep
实现根本不支持选择,但是它们几乎没有颜色支持。)grep
版本中,您无需设置 --color
选项,它是默认的。 - Jotne