如何查找文件中的重复行?

问题描述 投票:0回答:4

我有一个包含以下数据的输入文件:

line1
line2
line3
begin
line5
line6
line7
end
line9
line1
line3

我试图找到所有重复的行,我尝试过

sort filename | uniq -c  

但似乎对我不起作用:

它给了我:

  1 begin
  1 end
  1 line1
  1 line1
  1 line2
  1 line3
  1 line3
  1 line5
  1 line6
  1 line7
  1 line9

这个问题可能看起来重复,因为在文件中查找重复的行并计算每行重复的次数? 但输入数据的性质不同。

请建议。

sorting uniq
4个回答
8
投票

用这个:

sort filename | uniq -d
man uniq

0
投票

尝试

sort -u file

awk '!a[$0]++' file


0
投票

您必须稍微修改标准重复数据删除代码才能解决此问题:

如果您想要重复项的唯一副本,那么这是非常相同的想法:

  {m,g}awk 'NF~ __[$_]++' FS='^$'
  {m,g}awk '__[$_]++==!_'

如果您希望打印每个副本以实现重复,那么只要条件第一次产生,就打印2份副本,并一路打印新的匹配项。

通常,

first de-dupe

then sort
会更快,而不是相反。


0
投票
#!/usr/bin/env bash # Check if a file name is provided if [ $# -eq 0 ]; then echo "Usage: $0 [file]" exit 1 fi # File to check for duplicates file="$1" # Check if the file exists if [ ! -f "$file" ]; then echo "Error: File not found." exit 1 fi # Finding duplicates duplicates=$(sort "$file" | uniq -d) if [ -z "$duplicates" ]; then printf "\n%s\n" "No duplicates were found in $file." else printf "\n%s\n\n" "Duplicate lines in $file:" echo "$duplicates" fi
    
© www.soinside.com 2019 - 2024. All rights reserved.