Perl脚本删除连续重复单词的下一行

3

输入:

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;

但是它没有按照预期生成输出文件。请帮我解决问题。

它是反向的。它是为了指定输出文件不需要按顺序排列。 - Sumathi Gokul
2个回答

0
尝试使用这个正则表达式:
((line\d+)\s*:.*\n)\2

在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)

实际代码中的行名称和内容包含特殊字符。 - Sumathi Gokul
@SumathiGokul 好的,那么把 line\d+ 部分改成 .*? - Kaspar Lee

0

使用哈希表来完成它。

在迭代循环时,尝试使用:拆分行,因此使用模式匹配拆分行,如下所示:^.+?\K\s:

^表示匹配的开头

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

\K用于保留拆分后的单词。

然后将两个数据存储在$first$second中。通过$first值创建哈希键。这有助于消除重复项。最后,唯一的值存储在%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;

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接