我有一個文本檔案,其中有很多行,我需要在此檔案中搜索關鍵字,如果存在寫入日志檔案行,其中是關鍵字和關鍵字下方的一行和關鍵字上方的一行。現在搜索或寫關鍵字不起作用,如果找到全部寫,我不知道如何在下面和上面寫行。感謝您的一些建議。
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;
uj5u.com熱心網友回復:
下面的方法使用一個信號量變數和一個緩沖區變數來啟用所需的行為。
請注意,為了簡單測驗,使用的模式已替換為“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 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);
``
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/478973.html
