例如,考虑一个文件sensions.txt

This is sentence X
This is sentence Y
This is sentence X
This is sentence Y
This is sentence X
This is sentence Y
This is sentence X
This is sentence Y
This is sentence X
This is sentence Y
This is sentence X
This is sentence X
This is sentence Y
This is sentence Y

我们看到第一个This is sentence X就是This is sentence Y
有没有命令检查两行是否连续
This is sentence X后接This is sentence X
This is sentence Y后接This is sentence Y。在第11行和第12行中,我们看到2行是重复的。

最佳答案

您甚至不需要为此使用awk
您可以简单地使用uniq命令。

$ cat sentences.txt
This is sentence X
This is sentence Y
This is sentence X
This is sentence Y
This is sentence X
This is sentence Y
This is sentence X
This is sentence Y
This is sentence X
This is sentence Y
This is sentence X
This is sentence X
This is sentence Y
This is sentence Y

uniq -d sentences.txt
This is sentence X
This is sentence Y

说明:
uniq是一个非常方便的命令,它可以打印文件中的连续重复项,对它们进行计数等。这里我使用-d选项来打印重复的连续行。
奖金:
如果要添加在哪一行找到重复项,则可以使用以下命令:
$ cat -n sentences.txt
     1  This is sentence Y
     2  This is sentence X
     3  This is sentence Y
     4  This is sentence X
     5  This is sentence Y
     6  This is sentence X
     7  This is sentence Y
     8  This is sentence X
     9  This is sentence X
    10  This is sentence Y
    11  This is sentence Y
$ cat -n sentences.txt | uniq -f1 -d
     8  This is sentence X
    10  This is sentence Y

其中-f1用于忽略第一个字段(行号)
最后但并非最不重要的是,如果要打印所有重复项,请使用-D选项。
$ cat -n sentences.txt | uniq -f1 -D
     8  This is sentence X
     9  This is sentence X
    10  This is sentence Y
    11  This is sentence Y

关于linux - 是否有任何UNIX/Linux命令可以检查2行是否连续,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/48982619/

10-13 09:16