我有一个文件list.txt,像这样:
cat bear tree catfish fish bear
我需要删除文档中其他地方已经完全找到的任何行,可以是重复行,也可以在另一行中找到.例如,“熊”和“熊”的行是相同的,因此删除其中一行; “猫”可以完全在“鲶鱼”中找到,因此“猫”被删除.输出看起来像这样:
catfish tree bear
如何删除所有重复行,包括在列表中较长行中找到的行?
到目前为止,我有这个:
#!/bin/bash touch list.tmp while read -r line do found="$(grep -c $line list.tmp)" if [ "$found" -eq "1" ] then echo $line >> list.tmp echo $line" added" else echo "Not added." fi done < list.txt
解决方法
如果O(N ^ 2)不打扰你:
#!/usr/bin/env perl use strict; use warnings; use List::MoreUtils qw{any}; my @words; for my $word ( sort {length $b <=> length $a} do { my %words; my @words = <>; chomp @words; @words{@words} = (); keys %words; } ) { push @words,$word unless do { my $re = qr/\Q$word/; any {m/$re/} @words; }; } print "$_\n" for @words;
如果你想要O(NlogN)你必须使用某种特里方法.例如,使用后缀树:
#!/usr/bin/env perl use strict; use warnings; use Tree::Suffix; my $tree = Tree::Suffix->new(); my @words; for my $word ( sort {length $b <=> length $a} do { my %words; my @words = <>; chomp @words; @words{@words} = (); keys %words; } ) { unless ($tree->find($word)){ push @words,$word; $tree->insert($word); }; } print "$_\n" for @words;
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。