Perl - 子字符串关键字

问题描述 投票:0回答:1

我有一个文本文件,其中有很多行,我需要在该文件中搜索关键字,如果存在,则写入日志文件行,其中关键字是关键字,并且关键字下方一行,上方一行。现在,如果找到全部写入,则搜索或写入关键字不起作用,并且我不知道如何在下面和上面写行。谢谢你的一些建议。

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;
perl substring
1个回答
1
投票

下面的方法使用一个信号量变量和一个缓冲区变量来提供所需的行为。

请注意,为了简单测试,所使用的模式已替换为 A`。

#!/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 follows a pattern
    print $out_fh $line if (!$p_next);
    
    # toggle semaphore to print the next line
    $p_next = 1;

  } else {
    # pattern not found.
    
    # if pattern was not detected in both current and previous line.
    $p_line = $line if (!$p_next);
    $p_next = 0;
  }
}
close($in_fh);
close($out_fh);
© www.soinside.com 2019 - 2024. All rights reserved.