使用awk在文件中打印重复的行

use*_*663 8 awk sed

我要求在uniq -D选项不支持的文件中打印所有重复的行.所以我在考虑使用awk打印重复行的另一种方法.我知道,我们在awk中有一个选项,如下所示.

TESTFILE.TXT

apple
apple
orange
orange
cherry
cherry
kiwi
strawberry
strawberry
papaya
cashew
cashew
pista
Run Code Online (Sandbox Code Playgroud)

命令:

awk 'seen[$0]++' testfile.txt
Run Code Online (Sandbox Code Playgroud)

但上面只打印出唯一的重复行.我需要uniq -D命令检索的相同输出.

apple
apple
orange
orange
cherry
cherry
strawberry
strawberry
cashew
cashew
Run Code Online (Sandbox Code Playgroud)

Ed *_*ton 13

无需解析文件两次:

$ awk 'c[$0]++; c[$0]==2' file
apple
apple
orange
orange
cherry
cherry
strawberry
strawberry
cashew
cashew
Run Code Online (Sandbox Code Playgroud)

  • 这很聪明! (2认同)
  • ```awk'c [$ 0] ++ && c [$ 0] == 2'文件`''仅输出每个重复项一次 (2认同)

gle*_*man 5

如果您只想使用普通的 awk,则必须处理该文件两次:一次生成计数,一次消除计数等于 1 的行:

awk 'NR==FNR {count[$0]++; next} count[$0]>1' testfile.txt testfile.txt
Run Code Online (Sandbox Code Playgroud)