使用空行作为 grep 的上下文“组分隔符”

Mar*_*ter 12 grep colors perl

我需要带有上下文、颜色和空白行作为组分隔符的 grep 输出。在这个问题中,我学会了如何定义 custom group-separator,并且我已经像这样构建了我的 grep 命令:

grep --group-separator="" --color=always -A5
Run Code Online (Sandbox Code Playgroud)

但组分隔符实际上不是空的,而是仍然包含颜色代码(即[[36m[[K[[m[[K)。这是因为我正在使用--color=always. 但是我需要在我的 grep 命令中使用颜色,并且我需要将分隔符设为空行(以便进一步处理)

我怎样才能结合这两个条件?

bsd*_*bsd 10

如果您使用GREP_COLORS环境变量,您可以控制每种匹配类型的特定颜色。man grep解释变量的使用。

以下命令将打印彩色匹配,但在分隔组的行上没有任何内容,只有一个空行。通过管道,od你会看到比赛前后的颜色逃逸,但仅限\n\n于组分离。

GREP_COLORS='ms=01;31:mc=01;31:sl=:cx=:fn=35:ln=32:bn=32:se=' grep --group-separator="" --color=always -A5
Run Code Online (Sandbox Code Playgroud)

取消设置se组件将抑制组分隔符中的颜色打印。

由于我上面的示例使用GREP_COLORS了以下所有默认值,因此也可以使用。

GREP_COLORS='se=' grep --group-separator="" --color=always -A5
Run Code Online (Sandbox Code Playgroud)

如果您不使用bash类似的外壳,则可能需要先导出GREP_COLORS


ter*_*don 5

就个人而言,我使用 Perl 而不是grep. 我有一个小脚本可以突出显示给定的颜色模式:

#!/usr/bin/env perl
use Getopt::Std;
use strict;
use Term::ANSIColor; 

my %opts;
getopts('hsc:l:',\%opts);
    if ($opts{h}){
      print<<EoF; 
DESCRIPTION

$0 will highlight the given pattern in color. 

USAGE

$0 [OPTIONS] -l PATTERN FILE

If FILE is ommitted, it reads from STDIN.

-c : comma separated list of colors
-h : print this help and exit
-l : comma separated list of search patterns (can be regular expressions)
-s : makes the search case sensitive

EoF
      exit(0);
    }

my $case_sensitive=$opts{s}||undef; 
my @color=('bold red','bold blue', 'bold yellow', 'bold green', 
           'bold magenta', 'bold cyan', 'yellow on_magenta', 
           'bright_white on_red', 'bright_yellow on_red', 'white on_black');
## user provided color
if ($opts{c}) {
   @color=split(/,/,$opts{c});
}
## read patterns
my @patterns;
if($opts{l}){
     @patterns=split(/,/,$opts{l});
}
else{
    die("Need a pattern to search for (-l)\n");
}

# Setting $| to non-zero forces a flush right away and after 
# every write or print on the currently selected output channel. 
$|=1;

while (my $line=<>) 
{ 
    for (my $c=0; $c<=$#patterns; $c++){
    if($case_sensitive){
        if($line=~/$patterns[$c]/){
           $line=~s/($patterns[$c])/color("$color[$c]").$1.color("reset")/ge;
        }
    }
    else{
        if($line=~/$patterns[$c]/i){
          $line=~s/($patterns[$c])/color("$color[$c]").$1.color("reset")/ige;
        }
      }
    }
    print STDOUT $line;
}
Run Code Online (Sandbox Code Playgroud)

如果将其保存在路径中color,则可以通过运行获得所需的输出

grep --group-separator="" --color=never -A5 foo | color -l foo
Run Code Online (Sandbox Code Playgroud)

这样,脚本会为您着色匹配项,您可以告诉grep不要使用颜色并避免此问题。