in reply to Re: Searching for a string in a text and printing the next few lines
in thread Searching for a string in a text and printing the next few lines

guys guys guys....
spare me a thought :( I am just a naive finding my way into perl
I tried working something out but was nowhere, hence had to type the requirement
anyways, this is the code i tried..

#! /usr/local/bin/perl open (TEXT_FILE, "file1.txt"); while ($line = <TEXT_FILE>) { if ($line =~ m/ERROR/) { $c = 0; while ($c <= 10) { $nextline = <TEXT_FILE> ; printf ("$nextline"); $c = $c + 1; } } } close (TEXT_FILE);

and like you said vroom, if the search string is in multiple locations, I want to print all such instances, not just once..

  • Comment on Re^2: Searching for a string in a text and printing the next few lines
  • Download Code

Replies are listed 'Best First'.
Re^3: Searching for a string in a text and printing the next few lines
by ww (Archbishop) on Nov 13, 2009 at 12:20 UTC

    That's a good start.

    On quick inspection:

    1. Your script won't print the first instance of "ERROR" so you may wish to add a print $line at line 7.
    2. With that change, your script will print the first instance of "ERROR" but won't print the ten lines following a second instance, if that second instance is fewer than ten lines below the first. Is that your intent?
    3. Is there a reason for using printf rather than a simple print?

    You could use @array = open (TEXT_FILE, "file1.txt"); to read your file into an array and then test each element of the array rather than using while. That might make it easier to work out the logic needed to satisfy the "ten lines" requirement.

    AND, read perldoc -f open for the three argument form of open (and always test the open: or die "Can't open file1.txt: $!\n";).

    Life will also be easier if you use clear and consistent indenting (which of the various recommendations you follow is a matter of taste). Hint for posting here: "Preview, perview, preview! A string of spaces renders differently than a tab.

    You'll get better answers if you tell in detail what "nowhere" means, in terms of output, error & warnings messages and a better set of sample data (see my previous questions: you've answered some of them, but left some crucial elements of your spec to our crystal balls - most of which are still broken).