Home > Net >  Perl - substring keywords
Perl - substring keywords

Time:05-19

I have a text file where is lot of lines, I need search in this file keywords and if exist write to log file line where is keywords and line one line below and one above the keyword. Now search or write keyword not function if find write all and I dont known how can I write line below and above. Thanks for some advice.

my $vstup = "C:/Users/Omega/Documents/Kontroly/testkontroly/kontroly20220513_154743.txt";
my $log = "C:/Users/Omega/Documents/Kontroly/testkontroly/kontroly.log";
    
open( my $default_fh, "<", $vstup ) or die $!;
open( my $main_fh,    ">", $log )    or die $!;

my $var = 0;
while ( <$default_fh> ) { 
    if (/\Volat\b/)
        $var = 1;
    }
    if ( $var )
        print $main_fh $_;
    }
}

close $default_fh;
close $main_fh;

CodePudding user response:

The approach below use one semaphore variable and a buffer variable to enable the desired behavior.

Notice that the pattern used was replaced by 'A` for simplicity testing.

#!/usr/bin/perl

use strict;
use warnings;


my ($in_fh, $out_fh);
my ($in, $out);
$in = 'input.txt';
$out = 'output.txt';

open($in_fh, "< ", $in) || die $!."\n";
open($out_fh, "> ", $out) || die $!;

my $p_next = 0;
my $p_line;
while (my $line = <$in_fh>) {
  # print line after occurrence
  print $out_fh $line if ($p_next);

  if ($line =~ /A/) {
    if (defined($p_line)) {
      # print previous line
      print $out_fh $p_line;

      # once printed undefine variable to avoid printing it again in the next loop
      undef($p_line);
    }
    
    # Print current line if not already printed as the line following a pattern
    print $out_fh $line if (!$p_next);
    
    # toogle semaphore to print the next line
    $p_next = 1;

  } else {
    # pattern not found.
    
    # if pattern not detected in both current and previous line.
    $p_line = $line if (!$p_next);
    $p_next = 0;
  }
}
close($in_fh);
close($out_fh);
``
  • Related