bash中的独特线条

joh*_*ood 48 bash shell unique line

我绝对是bash的新手,所以这是我的问题:
从标准输入给出任意数量的文本行.
输出:非重复行数.

例如:
INPUT:

她穿着黑色的鞋子.
我叫Johny.
我讨厌星期一.
我叫Johny.
我不明白你.
她穿着黑色的鞋子.

OUTPUT:

2

Din*_*ing 110

您可以尝试使用uniq man uniq并执行以下操作

sort file | uniq -u | wc -l
Run Code Online (Sandbox Code Playgroud)

  • 它在man页面中说明:注意:'uniq'不会检测重复的行,除非它们是相邻的.您可能希望先对输入进行排序,或使用`sort -u'而不使用`uniq'.此外,比较遵守`LC_COLLATE'指定的规则.它也有效.... (19认同)

gle*_*man 8

这是我如何解决问题:

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

但那是非常不透明的.这是一个(稍微)更清晰的方式来看它(需要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
}
Run Code Online (Sandbox Code Playgroud)