How to match once per file in grep?

后端 未结 6 1109
再見小時候
再見小時候 2021-02-06 20:38

Is there any grep option that let\'s me control total number of matches but stops at first match on each file?

Example:

If I do this grep -ri --include \'*

6条回答
  •  难免孤独
    2021-02-06 21:03

    You can do this easily in perl, and no messy cross platform issues!

    use strict;
    use warnings;
    use autodie;
    
    my $match = shift;
    
    # Compile the match so it will run faster
    my $match_re = qr{$match};
    
    FILES: for my $file (@ARGV) {
        open my $fh, "<", $file;
    
        FILE: while(my $line = <$fh>) {
            chomp $line;
    
            if( $line =~ $match_re ) {
                print "$file: $line\n";
                last FILE;
            }
        }
    }
    

    The only difference is you have to use Perl style regular expressions instead of GNU style. They're not much different.

    You can do the recursive part in Perl using File::Find, or use find feed it files.

    find /some/path -name '*.coffee' -print0 | xargs -0 perl /path/to/your/program
    

提交回复
热议问题