我发现grep的——color=always标志非常有用。但是,grep只打印匹配的行(除非您要求上下文行)。假设它打印的每一行都有一个匹配项,那么高亮显示并不能增加尽可能多的功能。
我真的想猫一个文件,并看到整个文件与模式匹配突出显示。
是否有某种方法可以告诉grep打印正在读取的每一行,而不管是否有匹配?我知道我可以编写一个脚本来在文件的每一行上运行grep,但我很好奇标准grep是否可以做到这一点。
我发现grep的——color=always标志非常有用。但是,grep只打印匹配的行(除非您要求上下文行)。假设它打印的每一行都有一个匹配项,那么高亮显示并不能增加尽可能多的功能。
我真的想猫一个文件,并看到整个文件与模式匹配突出显示。
是否有某种方法可以告诉grep打印正在读取的每一行,而不管是否有匹配?我知道我可以编写一个脚本来在文件的每一行上运行grep,但我很好奇标准grep是否可以做到这一点。
当前回答
以下是我的方法,灵感来自@kepkin的解决方案:
# Adds ANSI colors to matched terms, similar to grep --color but without
# filtering unmatched lines. Example:
# noisy_command | highlight ERROR INFO
#
# Each argument is passed into sed as a matching pattern and matches are
# colored. Multiple arguments will use separate colors.
#
# Inspired by https://stackoverflow.com/a/25357856
highlight() {
# color cycles from 0-5, (shifted 31-36), i.e. r,g,y,b,m,c
local color=0 patterns=()
for term in "$@"; do
patterns+=("$(printf 's|%s|\e[%sm\\0\e[0m|g' "${term//|/\\|}" "$(( color+31 ))")")
color=$(( (color+1) % 6 ))
done
sed -f <(printf '%s\n' "${patterns[@]}")
}
这接受多个参数(但不允许自定义颜色)。例子:
$ noisy_command | highlight ERROR WARN
其他回答
我使用的rcg来自“Linux服务器黑客”,O'Reilly。它非常适合你想要的东西,可以用不同的颜色突出多个表情。
#!/usr/bin/perl -w
#
# regexp coloured glasses - from Linux Server Hacks from O'Reilly
#
# eg .rcg "fatal" "BOLD . YELLOW . ON_WHITE" /var/adm/messages
#
use strict;
use Term::ANSIColor qw(:constants);
my %target = ( );
while (my $arg = shift) {
my $clr = shift;
if (($arg =~ /^-/) | !$clr) {
print "Usage: rcg [regex] [color] [regex] [color] ...\n";
exit(2);
}
#
# Ugly, lazy, pathetic hack here. [Unquote]
#
$target{$arg} = eval($clr);
}
my $rst = RESET;
while(<>) {
foreach my $x (keys(%target)) {
s/($x)/$target{$x}$1$rst/g;
}
print
}
或者你也可以使用银色搜索器
ag <search> --passthrough
我使用以下命令来达到类似的目的:
grep -C 100 searchtext文件
这将说grep打印100 * 2行上下文,在高亮显示的搜索文本之前和之后。
另一个回答提到了grep的-Cn开关,其中包含n行Context。当egrep模式看起来太复杂,或者当我在一台没有安装rcg和/或ccze的机器上时,我有时会用n=99作为一种快速而肮脏的方式来获得[至少]满屏的上下文。
我最近发现ccze是一个更强大的着色剂。我唯一的抱怨是它是面向屏幕的(就像less一样,我从不使用这个原因),除非你为“原始ANSI”输出指定-A开关。
上面提到的RCG +1。它仍然是我的最爱,因为它是如此简单,自定义在一个别名。类似这样的东西通常在我的~/.bashrc中:
alias tailc='tail -f /my/app/log/file | rcg send "BOLD GREEN" receive "CYAN" error "RED"'
以下是我的方法,灵感来自@kepkin的解决方案:
# Adds ANSI colors to matched terms, similar to grep --color but without
# filtering unmatched lines. Example:
# noisy_command | highlight ERROR INFO
#
# Each argument is passed into sed as a matching pattern and matches are
# colored. Multiple arguments will use separate colors.
#
# Inspired by https://stackoverflow.com/a/25357856
highlight() {
# color cycles from 0-5, (shifted 31-36), i.e. r,g,y,b,m,c
local color=0 patterns=()
for term in "$@"; do
patterns+=("$(printf 's|%s|\e[%sm\\0\e[0m|g' "${term//|/\\|}" "$(( color+31 ))")")
color=$(( (color+1) % 6 ))
done
sed -f <(printf '%s\n' "${patterns[@]}")
}
这接受多个参数(但不允许自定义颜色)。例子:
$ noisy_command | highlight ERROR WARN