我正在嘗試在 perl 中使用正則運算式從輸入檔案中提取多行到僅包含 head 的輸出檔案行。邏輯是將行作為標記添加到陣列中,然后遍歷陣列進行頭部。在陣列中添加行作為標記時,遇到匹配正則運算式模式新行且沒有字符的問題。
my @arr = split("\n",$str);
foreach my $token (@arr) {
print "Inside for\n";
if($token =~ m[head])
{
print "Inside if";
print $token;
}
}
**File Content**
**InputFile.txt**
- text1
- text2
- head
- text4
- text5
- non head
- text8
- text9
- head
**OutputFile.txt**
- text1
- text2
- head
- text8
- text9
- head
uj5u.com熱心網友回復:
可以讀取段落中的輸入(-00 開關),如果真的總是像那里一樣的空白,并列印一個段落,如果它(在這種情況下以)所需的模式結束
perl -00 -wne'print if /\n\s*- head\s*\z/' file
我使用了\z 斷言,但$在給定的示例中也很好。
在腳本中,這是通過設定輸入記錄分隔符來完成的
use warnings;
use strict;
local $/ = "\n\n";
while (<>) {
print if /\n\s*- head\s*\z/;
}
我們希望local$/在整個運行程序中(在更大的程式中)不改變所有內容。
uj5u.com熱心網友回復:
當逐行讀取檔案時,可以使用“滑動視窗”技術來實作預期的輸出。
#!/usr/bin/perl
use warnings;
use strict;
my @buffer;
while (<>) {
if (/- head$/) {
print splice @buffer;
print;
} elsif (/^$/) { # Same as ("\n" eq $_)
@buffer = ("\n");
} else {
push @buffer, $_;
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/488110.html
