首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >计算替换重复值后的记录数

计算替换重复值后的记录数
EN

Stack Overflow用户
提问于 2017-04-23 06:38:03
回答 1查看 36关注 0票数 0

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

代码语言:javascript
复制
1000727888004
522101 John Smith
522101 John Smith
522188 Shelly King
522188 Shelly King
1000727888002
522990 John Doe
522990 John Doe
9000006000000

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

代码语言:javascript
复制
perl -ne 'print unless $dup{$_}++;' old_file.txt > new_file.txt

在我运行上面的命令后,它删除了重复的条目,但计数仍然如下所示:

代码语言:javascript
复制
1000727888004
522101 John Smith
522188 Shelly King
1000727888002
522990 John Doe
9000006000000

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

代码语言:javascript
复制
1000727888002
522101 John Smith
522188 Shelly King
1000727888001
522990 John Doe
9000003000000

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

谢谢!

EN

回答 1

Stack Overflow用户

发布于 2017-04-23 14:26:23

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

代码语言:javascript
复制
$ 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

输出:

代码语言:javascript
复制
1000727888002
522101 John Smith
522188 Shelly King
1000727888001
522990 John Doe
9000006000000

如果删除了整个文件中的重复项,并且最后一条记录也是计数:

代码语言:javascript
复制
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
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/43565387

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档