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

Hi Monks, I need a script to identify a given string in the log file and for every time i run the script it should check the occurance of string recently occured. Since the log file gets updating,so script should start searching the given string with the lastest data entered into the log file.
  • Comment on Need a script to identify a given string in a log file

Replies are listed 'Best First'.
Re: Need a script to identify a given string in a log file
by monarch (Priest) on Nov 10, 2008 at 05:42 UTC

    My recommended approach:

    • find all log files you wish to search (e.g. messages, messages.1, messages.2, and so forth)
    • order your list of log files from the most recent to the oldest, say in an array
    • for each file in your list search for your string
    • if you find your string, store it, but keep reading through the file in case you find a later occurrence
    • return the last found string, but if you didn't find the string then continue on to the next newest log file

    For ordering your files you could possibly do the following:

    my @files = glob( "/var/log/messages*" ); # sort by mtime my @sortedfiles = sort { ( stat($b) )[9] <=> ( stat($a) )[9] } @files;

    You could, of course, attempt to start from the tail of the log file and work your way backwards, but that is very hard work and may be an unnecessary optimisation.

Re: Need a script to identify a given string in a log file
by Lawliet (Curate) on Nov 10, 2008 at 05:35 UTC

    Well then you better start writing one. Unless, of course, you were implying something that is looked down upon here at PerlMonks. But you would never do that, right?

    Take a look at How do I post a question effectively?

    I'm so adjective, I verb nouns!

    chomp; # nom nom nom

Re: Need a script to identify a given string in a log file
by chrism01 (Friar) on Nov 10, 2008 at 08:35 UTC