這裏我試圖將文件從# start data
分割爲# end data
,如果字符串'Pen'或'Laptop'存在,則代碼應該繼續寫入文件,如果不是,則應該寫入文件進入輸出文件。perl中的文本文件操作
Input
# start data a1
Data1 Book 1234
Data1 Pen 54635
Data1 Laptop 4567
Data1 Lens 6473
# end data a1
# start data a2
Data2 Book 1234
Data2 Box 54635
Data2 Card 4567
Data2 Lens 6473
# end data a2
Expected ouput
# start data a2
Data2 Book 1234
Data2 Box 54635
Data2 Card 4567
Data2 Lens 6473
# end data a2
守則snipppet使用:
#!/usr/local/perl
use warnings;
use strict;
open(filein, "<Input.txt");
open(fileout, ">ouput.txt");
my @array;
my $strt =qr/^#\sstart\sdata/;
my $end=qr/^#\send\sdata/;
while(<filein>)
{
@array= split(/$strt/../$end/,$_);
foreach my $i(@array)
{
if($i =~ /Pen|Laptop/)
{
next;
}
else
{
print fileout "$_";
}
}
}
close(filein);
close(fileout);
Obtained Output from the above snippet
# start data a1
Data1 Book 1234
Data1 Book 1234
Data1 Pen 54635
Data1 Laptop 4567
Data1 Lens 6473
# end data a1
# start data a2
Data1 Book 1234
Data1 Book 1234
Data1 Box 54635
Data1 Box 54635
Data1 Card 4567
Data1 Card 4567
Data1 Lens 6473
# end data a2
嗨,你已經證明你的預期產出,而不是你的輸出電流,或你認爲問題是。你可以[編輯]你的問題,以清楚你需要什麼? – IMSoP
嗨,我已經更新了我從我的代碼得到的輸出。我認爲這主要是我用過的正則表達式的問題。請建議 – user8450886