【发布时间】:2017-04-16 10:53:16
【问题描述】:
这个问题不等于How to print only the unique lines in BASH?,因为那个问题建议删除重复行的所有副本,而这个问题只是关于消除重复行,即将1, 2, 3, 3 更改为1, 2, 3 而不是只是1, 2。
这个问题真的很难写,因为我看不出任何有意义的东西。但这个例子显然是直截了当的。如果我有这样的文件:
1
2
2
3
4
解析文件后删除重复的行,变成这样:
1
3
4
我知道 python 或其中的一些,这是我编写的用于执行它的 python 脚本。创建一个名为clean_duplicates.py 的文件并将其运行为:
import sys
#
# To run it use:
# python clean_duplicates.py < input.txt > clean.txt
#
def main():
lines = sys.stdin.readlines()
# print( lines )
clean_duplicates( lines )
#
# It does only removes adjacent duplicated lines, so your need to sort them
# with sensitive case before run it.
#
def clean_duplicates( lines ):
lastLine = lines[ 0 ]
nextLine = None
currentLine = None
linesCount = len( lines )
# If it is a one lined file, to print it and stop the algorithm
if linesCount == 1:
sys.stdout.write( lines[ linesCount - 1 ] )
sys.exit()
# To print the first line
if linesCount > 1 and lines[ 0 ] != lines[ 1 ]:
sys.stdout.write( lines[ 0 ] )
# To print the middle lines, range( 0, 2 ) create the list [0, 1]
for index in range( 1, linesCount - 1 ):
currentLine = lines[ index ]
nextLine = lines[ index + 1 ]
if currentLine == lastLine:
continue
lastLine = lines[ index ]
if currentLine == nextLine:
continue
sys.stdout.write( currentLine )
# To print the last line
if linesCount > 2 and lines[ linesCount - 2 ] != lines[ linesCount - 1 ]:
sys.stdout.write( lines[ linesCount - 1 ] )
if __name__ == "__main__":
main()
虽然,在搜索重复行时,删除似乎更容易使用 grep、sort、sed、uniq 等工具:
- How to remove duplicate lines inside a text file?
- removing line from list using sort, grep LINUX
- Find duplicate lines in a file and count how many time each line was duplicated?
- Remove duplicate entries in a Bash script
- How to delete duplicate lines in a file without sorting it in Unix?
- How to delete duplicate lines in a file...AWK, SED, UNIQ not working on my file
【问题讨论】:
-
重复行总是相邻吗?假设输入是 1, 2, 2, 3, 4, 2 - 4 之后的 2 是否应该出现在输出中?
-
是的,我在做之前对它们进行了排序,以便于编写代码。无论如何,最好是马上使用
uniq -u。 -
请注意,给定输入 1、2、2、3、4、2、
uniq -u将打印第二个 2;它仅适用于相邻的重复行。因此,预分类是一个好主意。另请注意,uniq采用零个或一个输入文件,如果有输入文件,它可以采用输出文件:uniq [-c|-d|-u] [-f fields] [-s char] [input_file [output_file]]根据 POSIX。它不是通用文件过滤器(通用文件过滤器采用零个或多个文件名并依次处理标准输入或每个文件名,写入标准输出)。 -
谢谢!
uniq文档具有误导性。我在这里测试过,它只删除相邻的行。 -
这能回答你的问题吗? How to print only the unique lines in BASH?