删除列2中包含重复条目的所有行

时间:2019-07-05 04:33:09

标签: awk

我有一个两列的大文件,我想根据第2列中的重复条目删除该行。我想删除这两个重复条目。

我尝试过:

awk '!seen[$2]++' filename

但是它只会删除一个重复项。

输入文件示例:

1  3
2  3
4  10
1  6
5  3

预期输出:

4  10
1  6

4 个答案:

答案 0 :(得分:3)

请您尝试以下。

awk '{seen[$2]++;value[$2]=$0} END{for(i in seen){if(seen[i]==1){print value[i]}}}' Input_file

答案 1 :(得分:2)

$ awk 'NR==FNR{cnt[$2]++; next} cnt[$2]==1' file file
4  10
1  6

或者如果您无法两次读取输入(例如,如果它来自管道),则:

$ awk '{rec[NR]=$0; key[NR]=$2; cnt[$2]++} END{for (i=1; i<=NR; i++) if (cnt[key[i]] == 1) print rec[i]}' file
4  10
1  6

答案 2 :(得分:0)

使用coreutilsgrep

# Sort on the second column
<infile sort -k2,2n | 

# Count number of repeated fields in the second column
uniq -f1 -c         | 

# Remove fields that are repeated
grep -E '^ +1 +'    | 

# Squeeze white-space
tr -s ' '           | 

# Remove repeat count
cut -d' ' -f3-

输出:

1 6
4 10

答案 3 :(得分:0)

另一个有sortuniqgrep的人:

$ grep -v -f <(sort -k2n file | uniq -f 1 -D) file
4  10
1  6

解释:sort在第二个字段上对file进行排序:

1  3
2  3
5  3
1  6
4  10

uniq -f 1 -D跳过第一个(空白行分隔)字段,仅打印重复的行:

1  3
2  3
5  3

该列表是grep的排除列表。