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

Hi, How do I look for only a particular line in a file. For ex: In a particular file error.log, I was look for a particular line "The dir is '/usr' and there are 23 files" and in the line "The dir is '/usr' and there are 23 files" .. I want to store /usr to an array. Thanks

Replies are listed 'Best First'.
Re: look for a word
by TedPride (Priest) on Jun 09, 2005 at 04:07 UTC
    use strict; use warnings; my @matches; while (<DATA>) { push @matches, $1 if m/The dir is '(.*?)'/; } print join "\n", @matches; __DATA__ sdfdfsddf The dir is '/usr' and there are 23 files sdfsdfdsdds The dir is '/bingo' and there are 16 files
Re: look for a word
by Zaxo (Archbishop) on Jun 09, 2005 at 04:09 UTC

    Do I understand correctly that '/usr' may vary?

    my @dirs; while (<>) { m/^The dir is '([^']*)' and there are \d* files/ and push @dirs, $1; }
    If the match is successful, the bit captured by parentheses between quotes is pushed onto @dirs. I've left out file opening and such by using the default diamond op. Read from an open handle for better control.

    After Compline,
    Zaxo

      Hello, Thank you for the reply, Yes the '/usr' may vary. It could be any other dir too like '/var'.
        Hi again, I am a beginner in perl and am not able to work this out. In the following string "05/27/05 03:03:30 ANS1802E The dir is '/usr' and there are 23 files" I want to be able to push the /usr to an array. I am not sure how to use the search pattern in perl.