perl脚本删除包含重复单词的下一行

时间:2016-03-30 10:10:56

标签: regex perl perl-module

输入:

DFF_2 : dff_0_2 port map(READY_c => READY_c, CT0 =>CT0);
\DFF_0\ : dff_0 port map(un1_CT1 => un1_CT1, CT2 =>CT2);
DFF_10 : dff_0_10 port map(MRVQN1 => MRVQN1, un1_CT2_1 =>GSMC_un1_CT2_1);
DFF_1 : dff_0_1 port map(un1_CT2_1 =>GSMC_un1_CT2_1);
DFF_1 : dff_0_1 port map(un1_CT2_1 =>un1_CT2_1);

预期输出1:

DFF_2 : dff_0_2 port map(READY_c => READY_c, CT0 =>CT0);
\DFF_0\ : dff_0 port map(un1_CT1 => un1_CT1, CT2 =>CT2);
DFF_10 : dff_0_10 port map(MRVQN1 => MRVQN1, un1_CT2_1 =>GSMC_un1_CT2_1);
DFF_1 : dff_0_1 port map(un1_CT2_1 =>un1_CT2_1);

预期输出2 :(无需按顺序排列,但应恢复更新的行)

DFF_1 : dff_0_1 port map(un1_CT2_1 =>un1_CT2_1);    
DFF_10 : dff_0_10 port map(MRVQN1 => MRVQN1, un1_CT2_1 =>GSMC_un1_CT2_1);
\DFF_0\ : dff_0 port map(un1_CT1 => un1_CT1, CT2 =>CT2);    
DFF_2 : dff_0_2 port map(READY_c => READY_c, CT0 =>CT0);

对于这种情况,我不能使用重复行删除perl脚本,因为字符串word8使用新字符串word10更新。我尝试反转内容并使用重复的单词来删除。但是,我的代码无法实现。

open (IN, "<input.txt") or die;
open (OUT, ">output.txt") or die;
my @reverse = reverse <IN>;
foreach (@reverse){
print OUT "@reverse\n"; }
close (IN);
close (OUT);  

output:

DFF_1 : dff_0_1 port map(un1_CT2_1 =>un1_CT2_1);    
DFF_1 : dff_0_1 port map(un1_CT2_1 =>GSMC_un1_CT2_1);
DFF_10 : dff_0_10 port map(MRVQN1 => MRVQN1, un1_CT2_1 =>GSMC_un1_CT2_1);
\DFF_0\ : dff_0 port map(un1_CT1 => un1_CT1, CT2 =>CT2);    
DFF_2 : dff_0_2 port map(READY_c => READY_c, CT0 =>CT0);




open (IN1, "<output.txt") or die;
open (OUT1, ">output1.txt") or die;
while (<IN1>){
my $save = "$1" if /(.+)\s\:/;
next if /$save\s/;
print OUT1 $_;}
close (IN1);
close (OUT1;

但它没有按预期生成输出文件。请帮助我。

2 个答案:

答案 0 :(得分:0)

试试这个RegEx:

((line\d+)\s*:.*\n)\2

Live Demo on Regex101

工作原理:

(          # Capture line to be removed
  (line\d+)  # Capture Line Name / Number (Group #2)
  \s*        # Optional Whitespace
  :          # : (Colon)
  .*         # Line Data
  \n         # Newline Character at end of Line
)
\2           # Next line starts with this Line Name (stored in Group #2)

答案 1 :(得分:0)

使用哈希来做到这一点。

迭代循环时尝试使用:分割线,所以使用模式匹配来分割线,如^.+?\K\s:

比赛开始时

^

+?有助于避免+的贪婪。

\K用于防止分裂。

然后将这两个数据存储在$first$second中。按$first值创建哈希键。它有助于删除重复。然后最后将uniq值存储到%hash中,然后使用grep格式化哈希值。

open my $fh,"<","one.txt";
my %hash;
while (<$fh>)
{   
    ($first,$second) = split(/^.+?\K\s:/);
    $hash{$first} = " : $second";

}

my @ar = grep{ $_ =$_.$hash{$_} }keys %hash;
print @ar;