使用脚本(bash、awk 或类似的)修剪文件中其他域的子域

Fab*_*bio 5 grep bash awk shell-script text-processing

我有一个巨大的文件(一万个条目),其中包含域(按随机顺序,但没有重复的域和任意数量的子域),这是一个小例子:

domain.com
domain.net
sub.domain.com
anotherdomain.com
a.b.c.d.e.domain.net
5.4.3.2.1.domain.org
4.3.2.1.domain.org
Run Code Online (Sandbox Code Playgroud)

编辑:http ://p.ip.fi/WRD-提供了一个适当的工作集(网页很慢,使用 wget p.ip.fi/WRD- 即时下载)。

我想“修剪”所有子域,即编写一个新文件,删除任何其他域的所有子域。在那个例子中,它应该像这样结束(不关心排序):

domain.com
domain.net
anotherdomain.com
4.3.2.1.domain.org
Run Code Online (Sandbox Code Playgroud)

sub.domain.com,a.b.c.d.e.domain.net5.4.3.2.1.domain.org被删除(作为domain.com,domain.net和 的子域4.3.2.1.domain.org),anotherdomain.com被保留,因为它只是一个不同的域。

我尝试了一些优化的不同方法,它们奏效了,但它们太慢了(很多小时),因为文件有 1 万个条目。要有用,它必须很快(最多 1 分钟左右)。这是我现在所拥有的:

> $TEMP_BLACKLIST
BL=`cat $BLACKLIST`
for ZONE1 in $BL; do
        KEEP=1
        # sed -e "1,/^$ZONE1$/d" -> optimization: print $BLACKLIST only *after* the $ZONE1 occourence
        # break                  -> optimization: quit the loop if not present
        for ZONE2 in `echo $BL | sed -e "1,/^$ZONE1$/d"`; do
                if [[ $ZONE1 == *.$ZONE2 ]] ; then
                        KEEP=0
                        break
                fi
        done
        if [ $KEEP = 1 ] ; then
                echo $ZONE1 >> $TEMP_BLACKLIST
        fi
done
mv $TEMP_BLACKLIST $BLACKLIST
Run Code Online (Sandbox Code Playgroud)

代码应该包含在 bash 脚本中,所以只是 bash,最终调用从它调用的一些常见的嵌入式脚本语言(awk、Perl 或其他东西)(没有自定义 C 代码)。

你知道有什么更好的方法吗?

roa*_*ima 3

这是另一个版本

sed 's/^/\./' file |
    rev |
    LC_ALL=C sort -u |
    awk 'p == "" || substr($0,1,length(p)) != p { print $0; p = $0 }' |
    rev |
    sed 's/^\.//'
Run Code Online (Sandbox Code Playgroud)

输入

domain.com
domain.net
sub.domain.com
anotherdomain.com
a.b.c.d.e.domain.net
5.4.3.2.1.domain.org
4.3.2.1.domain.org
b.c
a-b.c
b.b.c
btcapp.api.btc.com
btc.com
Run Code Online (Sandbox Code Playgroud)

输出

a-b.c
b.c
4.3.2.1.domain.org
btc.com
domain.com
anotherdomain.com
domain.net
Run Code Online (Sandbox Code Playgroud)

尝试使用您在http://p.ip.fi/WRD-推荐的数据集,我收集的源文件包含 59683 行,过滤列表有 34824 行。我看到 36 行应用于grep btc.com | wc -l过滤列表。