一个作业在服务器上运行,它创建如下所示的文件:
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,6在最后一行中应该是3,从9开始)。它应该如下所示:
1000727888002
522101 John Smith
522188 Shelly King
1000727888001
522990 John Doe
9000003000000我想不出任何逻辑来解决这个问题。我需要帮助。我是否可以运行另一个命令或在perl命令中添加一些内容来纠正计数。是的,我可以在Notepad++中打开文件并手动修复号码,但我正在尝试使其自动化。
谢谢!
发布于 2017-04-23 14:26:23
在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
1000727888001https://stackoverflow.com/questions/43565387
复制相似问题