I write this printfound subroutine to insert color start and end , it's a mess.now I have more needs to colorize matched pattern, I guess there must some module can do the work nicely.#!/bin/perl use Getopt::Std; use utf8::all; use v5.36; my %options; getopts("a",\%options); my $togrep = shift; $togrep = qr/$togrep/; my $lastfile = ""; local $/ = ""; sub printfound($found, $file, $lastfile){ print "#" x 10, "\n#$file\n" , "#" x 10, "\n" if $file ne $lastfil +e; my ($postmatch, @string); while ($found =~ /(?s)(.*?)(?-s)($togrep)/gp){ my $prematch = $1; my $match = $2; $postmatch = ${^POSTMATCH}; $match =~ s/^/\e[1;31m/mg; $match =~ s/$/\e[0m/mg; push @string, $prematch, $match; } push @string, $postmatch; print join '', @string; return $file } while (<>) { if ($options{a}){ $lastfile = printfound $_, $ARGV, $lastfile if /$togrep/i; }else{ $lastfile = printfound $_, $ARGV, $lastfile if /\A.*$togrep/i; } } if ($!) { die "unexpected error while reading from: $!"; }
In reply to grep with color module of perl by vincentaxhe
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |