简体   繁体   English

如何使用 perl 脚本从文件中删除选定的重复行

[英]How to delete selected duplicated line from file using perl script

Let's say I am having file a.txt which is having following content.假设我的文件 a.txt 包含以下内容。

aa
aa
bb
cc
dd
ee
ff
ee
gg

I want following output -我想关注 output -

aa
aa
bb
cc
dd
ee
ff
gg

Note that I want delete particular duplication of lines only: ee .请注意,我只想删除特定的重复行: ee How can I do that following one liner I tried.在我尝试过的一个班轮之后,我怎么能做到这一点。

perl -ne 'print unless $a{$_}++' a.txt

but it is deleting all duplicated lines.但它正在删除所有重复的行。

To remove duplicates of only specific ("target") lines add that condition要删除仅特定(“目标”)行的重复项,请添加该条件

perl -lne'$tgt = "ee"; print unless $h{$_}++ and $_ eq $tgt' file

If there may be multiple such targets, then check whether the current line matches any one of them.如果可能有多个这样的目标,则检查当前行是否与其中任何一个匹配。 A nice tool for that is any from List::Util一个很好any工具是List::Util

perl -MList::Util=any -lne'
    $line=$_; 
    @tgt = qw(ee aa); 
    print unless $h{$line}++ and any { $_ eq $line} @tgt
' file

Target(s) can be read from the command line as arguments, if there is a benefit to not have them hardcoded.目标可以从命令行读取为 arguments,如果不对其进行硬编码有好处的话。

Note: In older versions any is in List::MoreUtils , and not in List::Util .注意:在旧版本中, any都在List::MoreUtils中,而不是在List::Util中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM