Colorized grep — viewing the entire file with highlighted matches

前端 未结 21 2495
野趣味
野趣味 2020-11-28 00:17

I find grep\'s --color=always flag to be tremendously useful. However, grep only prints lines with matches (unless you ask for context lines). Give

21条回答
  •  猫巷女王i
    2020-11-28 00:31

    I use rcg from "Linux Server Hacks", O'Reilly. It's perfect for what you want and can highlight multiple expressions each with different colours.

    #!/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
    }
    

提交回复
热议问题