非重复行的数量-唯一计数

50
这里是我的问题:从标准输入中给出任意数量的文本行。 输出:不重复行的数量 输入:
She is wearing black shoes.
My name is Johny.
I hate mondays.
My name is Johny.
I don't understand you.
She is wearing black shoes.

输出:

2
2个回答

114

你可以尝试使用uniq man uniq并按照以下步骤操作

sort file | uniq -u | wc -l

1
我在其中加入了“sort”命令。很好的发现...我把它放错了位置。 - Ding
20
在man手册中指出:注意:'uniq'只有在行是相邻的情况下才能检测到重复的行。您可能需要首先对输入进行排序,或者使用sort -u'而不是使用uniq'。此外,比较遵守由`LC_COLLATE'指定的规则。这也起作用了... - nils petersohn
1
在我的情况下,对于相同的文件,执行 sort file | uniq -usort -u file 会得到不同的输出。sort -u file 给出了正确的输出。 - Zimano

8
这是我解决问题的方法:

... | awk '{n[$0]++} END {for (line in n) if (n[line]==1) num++; print num}'

但这很难理解。以下是一个(稍微)更加易于理解的方式来查看它(需要bash版本4)

... | {
    declare -A count    # count is an associative array

    # iterate over each line of the input
    # accumulate the number of times we've seen this line
    #
    # the construct "IFS= read -r line" ensures we capture the line exactly

    while IFS= read -r line; do
        (( count["$line"]++ ))
    done

    # now add up the number of lines who's count is only 1        
    num=0
    for c in "${count[@]}"; do
        if (( $c == 1 )); then
            (( num++ ))
        fi
    done

    echo $num
}

在我的99年的机器上,awk解决方案运行得非常顺畅。 - fiorentinoing
@sfiore,什么是“99机器”? - glenn jackman

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接