【问题标题】:Count the Number of Records after Replacing Duplicate Values计算替换重复值后的记录数
【发布时间】:2017-09-19 19:04:42
【问题描述】:

一个作业在服务器上运行,它会创建一个如下所示的文件:

1000727888004
522101 John Smith
522101 John Smith
522188 Shelly King
522188 Shelly King
1000727888002
522990 John Doe
522990 John Doe
9000006000000

目前,我们正在修复代码,但这需要一个月的时间。同时,我正在使用命令删除重复记录,如下所示。

perl -ne 'print unless $dup{$_}++;' old_file.txt > new_file.txt

运行上述命令后,它会删除重复的条目,但计数仍如下:

1000727888004
522101 John Smith
522188 Shelly King
1000727888002
522990 John Doe
9000006000000

以 1 开头的行的最后一个数字是总计数(因此,第一行中的 4 应该是 2,第四行中的 2 应该是 1,从 9 开始的最后一行中的 6 应该是 3)。它应该如下所示:

1000727888002
522101 John Smith
522188 Shelly King
1000727888001
522990 John Doe
9000003000000

我想不出任何可以解决它的逻辑。我在这里需要帮助。我可以运行另一个命令或在我的 perl 命令中添加一些东西来更正计数。是的,我可以在 Notepad++ 中打开文件并手动修复数字,但我正在尝试使其自动化。

谢谢!

【问题讨论】:

  • 最后一条记录是什么,从 9 开始?
  • 即总计数文件的预告片。前 9 始终存在,然后接下来的 6 个数字是计数。如果它是一位数,则在左侧填充 5 个零。最后 6 个数字总是 0

标签: linux unix command-line-arguments


【解决方案1】:

在 awk 中。它处理计数记录之间的“块”内的欺骗,即。它不考虑整个文件中的重复项。如果这是不正确的假设,请告诉我。

$ awk '
NF==1 {          # for the cout record 
    if(c!="")    # this fixes leading empty row
        print c  # print count
    for(i in a)  # all deduped data records
        print i  # print them
    delete a     # empty hash
    c=$0         # store count (well, you could use just the first count record)
    next         # for this record don't process further
}
{
    if($0 in a)  # if current record is already in a
        c--      # decrease count
    else a[$0]   # else hash it
}
END {            # last record handling
    print c      # print the last record
    for(i in a)  # just in case last record would be missing
        print i  # this and above could be removes
}' file

输出:

1000727888002
522101 John Smith
522188 Shelly King
1000727888001
522990 John Doe
9000006000000

如果整个文件中的欺骗被删除并且最后一条记录也是计数:

awk '
NF==1 {
    if(NR==1)
        c=$0
    print c
} 
NF>1 {
    if($0 in a)
        c--
    else {
        a[$0]
        print
    }
}' file
1000727888004
522101 John Smith
522188 Shelly King
1000727888002
522990 John Doe
1000727888001

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-05-12
    • 1970-01-01
    • 2014-04-08
    • 2014-11-07
    • 2018-02-17
    • 2012-09-13
    • 1970-01-01
    相关资源
    最近更新 更多