tos has asked for the wisdom of the Perl Monks concerning the following question:

Dear Monks,

given : n files named 'kn' in different directories 'nc05*'.

# echo nc05*/kn nc05xa01/kn nc05xa02/kn nc05xa03/kn nc05xa04/kn nc05xa05/kn nc05xa06/k +n nc05xn01/kn
in the bash it's very easy to retrieve a certain customer-number somewhere in this files with a compact grep-command
# grep 10450676 nc05*/kn nc05xa02/kn:10450676 130//0004208/06//50668 371669346 371851024
I would like to do this in perl in a manner which is similar compact.

any suggestions ?

Replies are listed 'Best First'.
Re: searching a string in many files
by broquaint (Abbot) on Jun 25, 2003 at 13:57 UTC
    You can do this simply and compactly with File::Find::Rule
    use File::Find::Rule; my @files = find( file => name => 'kn', grep => qr/10450676/, in => [ glob('nc05*/') ] );
    Check out the File::Find::Rule docs for more info on this fantabulous module.
    HTH

    _________
    broquaint

Re: searching a string in many files
by pzbagel (Chaplain) on Jun 25, 2003 at 13:47 UTC
    perl -ne 'print "$ARGV: $_" if /10450676/' nc05*/kn

    :D

    P.S. Please note that based on my own uses of perl vs grep on gigabytes worth of log files, perl is much, MUCH faster than grep. And another note, unix shells have limits to the length of the command line you submit, that is, the length of the line after it interprets your glob 'nc05*/kn'. If you only have 10 or 20 directories, I wouldn't worry, if you have 100 or 1000, you will probably reach that maximum(Don't worry, I know at least bash will complain.) Get familiar with xargs for that case:

    ls nc05*/kn | xargs -n 10 perl -ne 'print "$ARGV: $_" if /10450676/'

    Addendum: Updated to make perl print the actual filename just like grep would.

      Excellent post, but I have one [extremely] minor niggle. The use of -n 10 in your xargs command is most likely superfluous. Most of the time xargs can figure out by itself the maximum number of options it can pack onto a single command line. Setting an arbitrary number (especially one as low as 10) could potentially cause xargs to call perl far more times than necessary.

        I did not know that about xargs. That's the second new thing I learned today. Boy does my brain need to cool off now. But seriously, ++ and thanks for the tip.

        Later