我想使用帶有正則運算式的 grep 來匹配一行的一部分,然后繼續列印該行和接下來的 2 行。但我不想在匹配后的第二行包含另一個正則運算式模式的情況下列印任何匹配。
示例文本:
If the line was there is a loom in the gloom
would you want that line printed?
Just trying to understand if you're just
other than as part of gloom
if you really do want to exclude lines
even when loom appears on it's own elsewhere on the line
尋找模式,憂郁;使用grep -Pn -A2 '^.*\b(gloom)\b.*$' *將列印
If the line was there is a loom in the gloom
would you want that line printed?
Just trying to understand if you're just
..和
other than as part of gloom
if you really do want to exclude lines
even when loom appears on it's own elsewhere on the line
但我不想在第三行列印包含單詞, others的第二組。使用 Perl 正則運算式。
uj5u.com熱心網友回復:
這是 Perl 中的一個示例:
use v5.20.0; # signatures requires perl >= 5.20
use feature qw(say);
use strict;
use warnings;
use experimental qw(signatures);
{
my $lines = read_file('file.txt');
for my $i (0..$#$lines) {
my $line = $lines->[$i];
if ($line =~/\b(gloom)\b/) {
if (!match_second_pattern($lines, $i)) {
print_block($lines, $i);
}
}
}
}
sub print_block($lines, $i) {
my $N = $#$lines;
for my $j (0..2) {
last if $i $j > $N;
print $lines->[$i $j];
}
}
sub match_second_pattern($lines, $i) {
my $N = $#$lines;
return 0 if ($i 2) > $N;
return $lines->[$i 2] =~ /elsewhere/;
}
sub read_file( $fn ) {
open ( my $fh, '<', $fn ) or die "Could not open file '$fn': $!";
my @lines = <$fh>;
close $fh;
return \@lines;
}
uj5u.com熱心網友回復:
這種型別的問題通常使用負前瞻來解決。不幸的是,我不相信你可以讓命令列grep跨越行邊界向前看,所以這需要一個 Perl 程式來完成:
#!/usr/bin/perl
use strict;
my $s = "If the line was there is a loom in the gloom
would you want that line printed?
Just trying to understand if you're just
other than as part of gloom
if you really do want to exclude lines
even when loom appears on it's own elsewhere on the line";
while ($s =~ /^.*?\bgloom\b(?!.*\n.*\n.*?\belsewhere\b).*\n.*\n.*\n?/mg) {
print "$&";
}
見 Perl 演示
請參閱正則運算式演示
如果要將輸入行上的輸入指定為來自 stdin 或檔案,則:
#!/usr/bin/perl -w
use strict;
my $s = '';
# read from stdin or the file specified on the command line:
while (<>) {
$s .= $_ ;
}
while ($s =~ /^.*?\bgloom\b(?!.*\n.*\n.*?\belsewhere\b).*\n.*\n.*\n?/mg) {
print "$&";
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/325976.html
上一篇:如何將perl程式拆分為多個檔案
下一篇:Perl遞回解釋
