如何通过linux工具完全删除重复的行,如grep,sort,sed,uniq?

use*_*ser 4 python awk grep sed uniq

如何通过linux工具完全删除重复的行,如grep,sort,sed,uniq?

这个问题真的很难写,因为我看不出任何能给它带来意义的东西.但这个例子显然是直截了当的.如果我有这样的文件:

1
2
2
3
4
Run Code Online (Sandbox Code Playgroud)

在解析删除重复行的文件之后,变成这样:

1
3
4
Run Code Online (Sandbox Code Playgroud)

我知道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()
Run Code Online (Sandbox Code Playgroud)

虽然,在搜索重复行时,删除似乎更容易使用工具如grep,sort,sed,uniq:

  1. 如何删除文本文件中的重复行?
  2. 使用sort,grep LINUX从列表中删除行
  3. 在文件中查找重复的行并计算每行复制的时间长度?
  4. 使用Bash脚本删除重复的条目
  5. 如何在Unix中删除文件中的重复行?
  6. 如何删除文件中的重复行... AWK,SED,UNIQ无法处理我的文件

Moi*_*dri 8

您可以使用uniq-u/ --unique选项.根据uniq手册页:

-u / --unique

不要输出在输入中重复的行.
仅打印I​​NPUT中唯一的行.

例如:

cat /tmp/uniques.txt | uniq -u
Run Code Online (Sandbox Code Playgroud)

或者,如UUOC所述:无用的猫,更好的方法是这样做:

uniq -u /tmp/uniques.txt
Run Code Online (Sandbox Code Playgroud)

这两个命令都会返回值:

1
3
4
Run Code Online (Sandbox Code Playgroud)

其中/tmp/uniques.txt保存问题中提到的数字,即

1
2
2
3
4
Run Code Online (Sandbox Code Playgroud)

注意:uniq要求对文件内容进行排序.如文档中所述:

默认情况下,uniq在排序文件中打印唯一行,它会丢弃除了一个相同的连续输入行之外的所有.这样OUTPUT包含唯一的行.

如果文件未排序,则首先需要sort内容,然后使用uniq已排序的内容:

sort /tmp/uniques.txt | uniq -u
Run Code Online (Sandbox Code Playgroud)

  • 参见[UUoC:无用的`cat`](/sf/ask/819738671/). (2认同)