Search code examples
perlgrepwc

How to use bash's grep in perl?


I would like to run the following unix command in perl:

grep -r "some_word" /path/to/directory | wc -l

(The goal is to see how many times does "some_word" appear in a directory and all its inside-folders/files.

What is Perl's equvalence? I tried looking here, but not enough examples for what I need.

For example, this is what I have:

/tmp/a/text1:
"This is a big text"

/tmp/a/text2:
"This is another text"

/tmp/b/text3:
"One more big text"

/tmp/a/a2/text4:
"Last big text"

and I would like to be able to run the grep command and I shall get:

grep_command_in_perl -r "big" /tmp/ | wc -l
3

Thanks! :)

*** EDIT: *** (I don't understand why the question was closed... What kind of expectation was expected from me? Is "grep -r "some_word" /path/to/directory | wc -l" not enough to understand what I'm asking?


Solution

  • Here is an example of how you can count the number of lines matching the word some_word in all files in directory /path/to/directory and its sub directories recursively. This is the equivalent of grep -r some_word /path/to/directory | wc -l:

    use feature qw(say);
    use strict;
    use warnings;
    use File::Find;
    
    {
        my $dir = '/path/to/directory';
        my $count = 0;
        my $word = 'some_word';
        find(sub { wanted($_, \$count, $word) }, $dir);
        say $count;
    }
    
    sub wanted {
        my ( $fn, $count, $word ) = @_;
        return if !-f $_;
        open ( my $fh, '<', $fn ) or die "Could not open file '$fn': $!";
        while( my $line = <$fh> ) {
            $$count++ if $line =~ /$word/;
        }
        close $fh;
    }
    

    If you want to interpret $word literally (escape regex meta characters like *, ), ..., and so on) use /\Q$word\E/ instead of /$word/