컨텍스트, 색상 및 빈 줄을 그룹 구분 기호로 사용하여 grep 출력이 필요합니다. 이 질문 에서 custom을 정의하는 방법을 배웠고 다음 group-separator
과 같이 grep 명령을 구성했습니다.
grep --group-separator="" --color=always -A5
그러나 그룹 구분 기호는 실제로 비어 있지 않으며 대신 여전히 색상 코드 (예 :)를 포함합니다 [[36m[[K[[m[[K
. 내가 사용하고 있기 때문 --color=always
입니다. 그러나 grep 명령에 색상이 필요하고 구분 기호가 빈 줄이되어야합니다 (추가 처리).
이 두 조건을 어떻게 결합 할 수 있습니까?
답변
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
se
구성 요소를 설정 해제하면 그룹 분리기에서 색상이 인쇄되지 않습니다.
위의 예 GREP_COLORS
에서 다음에 대한 모든 기본값이 사용되었으므로 다음과 같이 작동합니다.
GREP_COLORS='se=' grep --group-separator="" --color=always -A5
bash
유사한 쉘을 사용하지 않는 경우 GREP_COLORS
먼저 내 보내야합니다.
답변
개인적으로, 나는 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;
}
로 경로에 저장 color
하면 원하는 결과를 얻을 수 있습니다.
grep --group-separator="" --color=never -A5 foo | color -l foo
그렇게하면 스크립트가 일치하는 항목을 채색하므로 grep
색상을 사용하지 말고이 문제를 피할 수 있습니다.