我发现grep的——color=always标志非常有用。但是,grep只打印匹配的行(除非您要求上下文行)。假设它打印的每一行都有一个匹配项,那么高亮显示并不能增加尽可能多的功能。

我真的想猫一个文件,并看到整个文件与模式匹配突出显示。

是否有某种方法可以告诉grep打印正在读取的每一行,而不管是否有匹配?我知道我可以编写一个脚本来在文件的每一行上运行grep,但我很好奇标准grep是否可以做到这一点。


当前回答

这里有一些类似的东西。很有可能,无论如何你都会用得更少,所以试试这个:

less -p pattern file

它将突出显示该模式,并跳转到该模式在文件中第一次出现的位置。

你可以用n跳到下一个出现点,用p跳到前一个出现点,用q退出。

其他回答

我使用的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
}

另一个回答提到了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"'

是否有某种方法可以告诉grep打印正在读取的每一行 不管是否匹配?

Option -C999 will do the trick in the absence of an option to display all context lines. Most other grep variants support this too. However: 1) no output is produced when no match is found and 2) this option has a negative impact on grep's efficiency: when the -C value is large this many lines may have to be temporarily stored in memory for grep to determine which lines of context to display when a match occurs. Note that grep implementations do not load input files but rather reads a few lines or use a sliding window over the input. The "before part" of the context has to be kept in a window (memory) to output the "before" context lines later when a match is found.

模式,如^| pattern或pattern |$或任何空匹配的子模式,如[^ -~]?|PATTERN是一个很好的技巧。然而,1)这些模式不会显示不匹配的行作为上下文突出显示,2)这不能与其他一些grep选项组合使用,例如-F和-w。

所以这些方法都不能让我满意。我使用ugrep,并使用选项-y增强grep,以有效地将所有不匹配的输出显示为彩色高亮的上下文行。其他类似grep的工具,如ag和ripgrep也提供了一个传递选项。但是ugrep与GNU/BSD grep兼容,并提供了grep选项的超集,如-y和-Q。例如,下面是选项-y与-Q结合时显示的内容(输入模式的交互式查询UI):

ugrep -Q -y FILE ...

我想推荐ack——它比grep更好,是程序员的强大搜索工具。

$ ack --color --passthru --pager="${PAGER:-less -R}" pattern files
$ ack --color --passthru pattern files | less -R
$ export ACK_PAGER_COLOR="${PAGER:-less -R}"
$ ack --passthru pattern files

我喜欢它,因为它默认为递归搜索目录(并且比grep -r聪明得多),支持完整的Perl正则表达式(而不是POSIXish正则表达式(3)),并且在搜索许多文件时具有更好的上下文显示。

如果您想用不同的颜色突出显示几个模式,请参阅这个bash脚本。

基本用法:

echo warn error debug info 10 nil | colog

你可以改变图案和颜色,同时运行按一键,然后进入键。