我发现grep的——color=always标志非常有用。但是,grep只打印匹配的行(除非您要求上下文行)。假设它打印的每一行都有一个匹配项,那么高亮显示并不能增加尽可能多的功能。
我真的想猫一个文件,并看到整个文件与模式匹配突出显示。
是否有某种方法可以告诉grep打印正在读取的每一行,而不管是否有匹配?我知道我可以编写一个脚本来在文件的每一行上运行grep,但我很好奇标准grep是否可以做到这一点。
我发现grep的——color=always标志非常有用。但是,grep只打印匹配的行(除非您要求上下文行)。假设它打印的每一行都有一个匹配项,那么高亮显示并不能增加尽可能多的功能。
我真的想猫一个文件,并看到整个文件与模式匹配突出显示。
是否有某种方法可以告诉grep打印正在读取的每一行,而不管是否有匹配?我知道我可以编写一个脚本来在文件的每一行上运行grep,但我很好奇标准grep是否可以做到这一点。
当前回答
使用ripgrep,即rg: https://github.com/BurntSushi/ripgrep
rg - passthru……
颜色是默认的:
rg -t tf -e 'key.*tfstate' -e dynamodb_table
--passthru
Print both matching and non-matching lines.
Another way to achieve a similar effect is by modifying your pattern to
match the empty string.
For example, if you are searching using rg foo then using
rg "^|foo" instead will emit every line in every file searched, but only
occurrences of foo will be highlighted.
This flag enables the same behavior without needing to modify the pattern.
亵渎神明,没错,但格雷普已经沾沾自喜了。
安装ripgrep
你再也回不去了。
其他回答
使用着色程序:http://nojhan.github.io/colout/
它的目的是为文本流添加颜色高亮。给定一个正则表达式和一个颜色(例如:"red"),它会重新生成匹配突出显示的文本流。例句:
# cat logfile but highlight instances of 'ERROR' in red
colout ERROR red <logfile
你可以链接多个调用来添加多个不同的颜色高亮:
tail -f /var/log/nginx/access.log | \
colout ' 5\d\d ' red | \
colout ' 4\d\d ' yellow | \
colout ' 3\d\d ' cyan | \
colout ' 2\d\d ' green
或者你可以通过使用带有N个组的正则表达式(正则表达式的括号部分)来实现同样的事情,后面跟着一个逗号分隔的N种颜色列表。
vagrant status | \
colout \
'\''(^.+ running)|(^.+suspended)|(^.+not running)'\'' \
green,yellow,red
我把这个添加到我的.bash_aliases中:
highlight() {
grep --color -E "$1|\$"
}
使用ripgrep,即rg: https://github.com/BurntSushi/ripgrep
rg - passthru……
颜色是默认的:
rg -t tf -e 'key.*tfstate' -e dynamodb_table
--passthru
Print both matching and non-matching lines.
Another way to achieve a similar effect is by modifying your pattern to
match the empty string.
For example, if you are searching using rg foo then using
rg "^|foo" instead will emit every line in every file searched, but only
occurrences of foo will be highlighted.
This flag enables the same behavior without needing to modify the pattern.
亵渎神明,没错,但格雷普已经沾沾自喜了。
安装ripgrep
你再也回不去了。
我使用以下命令来达到类似的目的:
grep -C 100 searchtext文件
这将说grep打印100 * 2行上下文,在高亮显示的搜索文本之前和之后。
我使用的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
}