2012-01-28 107 views

回答

4

可以sort输入和传递给uniq -c

$ sort input_file | uniq -c 
2 a 
2 b 
1 f 
1 g 
1 z 

如果你想在右边的数字,使用awk他们进行切换:

$ sort input_file | uniq -c | awk '{print $2, $1}' 
a 2 
b 2 
f 1 
g 1 
z 1 

或者,做整个事情awk

$ awk ' 
{ 
    ++count[$1] 
} 
END { 
    for (word in count) { 
     print word, count[word] 
    } 
} 
' input_file 
f 1 
g 1 
z 1 
a 2 
b 2 
1
cat text | sort | uniq -c 

应该做的工作

+2

http://uuoc.com/ – Johnsyweb 2012-01-28 10:21:03

1

尝试:

awk '{ freq[$1]++; } END{ for(c in freq) { print c, freq[c] } }' test.txt 

凡test.txt的将是你的输入文件。

1

这是一个bash-only版本(需要bash版本4),使用associative array

#! /bin/bash 

declare -A count 
while read val ; do 
    count[$val]=$((${count[$val]} + 1)) 
done < your_intput_file # change this as needed 

for key in ${!count[@]} ; do 
    echo $key ${count[$key]} 
done 
+0

要求bash版本4用于关联数组 – 2012-01-28 14:54:31

+0

简单:'((count [$ val] ++))'。另外,你应该几乎总是在'read'中使用'-r'。总是引用变量:'用于键入$ {!count [@]}“'和'echo'$ key $ {count [$ key]}”'。 – 2012-01-28 16:40:10

0

这可能会为你工作:

cat -n file | 
sort -k2,2 | 
uniq -cf1 | 
sort -k2,2n | 
sed 's/^ *\([^ ]*\).*\t\(.*\)/\2 \1/' 

此输出在它们出现的顺序每串出现的次数。

相关问题