1

Im using grep for searching pattern in huge log files, since it's a log file and i want to see what's going on around the matches, i usually do grep -C 3 -color ...

however, after reading a lot of logs i find a little annoying to distinguish between every 7 lines, which line belongs to which match, so i want to find a way to distinguish between each matches (and the 6 lines surround it)

the thing i think would be helpful and easier for my eyes to read is to make each match in a different color - of course not really a new color for each match but just pick a few colors, let's say 3 colors such that matches will be colored in that sequence of colors, for example if I got 4 matches they will be colored as the following:

prefix1 match1 // purple color: start prefix2 match1 prefix3 match1 match1: suffix1 match1 suffix2 match1 suffix3 match1 // purple color: end prefix1 match2 // blue color: start prefix2 match2 prefix3 match2 match2: suffix1 match2 suffix2 match2 suffix3 match2 // blue color: end prefix1 match3 // green color: start prefix2 match3 prefix3 match3 match3: suffix1 match3 suffix2 match3 suffix3 match3 // green color: end prefix1 match4 // purple color: start prefix2 match4 prefix3 match4 match4: suffix1 match4 suffix2 match4 suffix3 match4 // purple color: end 

7 lines each color

So what essentially im looking for is a way to tell grep to do that, or a command to redirect grep to so that it will be colored as above

1
  • Not quite a duplicate, but relevant: Multicolored Grep Commented Dec 20, 2022 at 11:14

1 Answer 1

2

Like this using Perl and core Term::ANSIColor (installed by default):

<COMMAND> | perl -MTerm::ANSIColor=:constants -pe ' BEGIN{ our @colors = (MAGENTA, BLUE, GREEN); our @cols; } @cols = @colors if not scalar @cols; my $color = shift @cols if /^$/ or $. == 1; print $color; END{ print RESET } ' 

Or even shorter, Thanks @Terdon:

<COMMAND> | perl -MTerm::ANSIColor=:constants -00 -pe ' BEGIN{ @colors = (GREEN, MAGENTA, BLUE) } print $colors[$.%($#colors+1)]; END{ print RESET } ' 

enter image description here

Check color capabilities:

perldoc Term::ANSIColor

1
  • Easier to read and more robust using the core module Term::ANSIColor Commented Dec 20, 2022 at 18:28

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.