#! /bin/bash
#文件名:word_freg.sh
#用途:计算文件中单词的词频
if [ $# -ne 1 ]
then
echo "Usage:$0 filename"
exit -1
fi
filename=$1
egrep -o "\b[[:alpha:]]+\b" $filename | \
awk '{ count[$0]++ }
END{ printf("%-14s%s\n","word","count")
for(ind in count){
printf("%-14s%d\n",ind,count[ind])
}
}'
输出如下:
[root@server script01]# bash word_freg.sh words.txt
word count
used 1
this 2
counting 1
说明:
egrep -o "\b[[:alpha:]]+\b" $filename | \ #用于输出单词,-o选项打印出自由换行符分割的匹配字符序列。
\b:单词边界标记符
[:alpha:]:表示字母的字符类。
awk命令用来避免对每一个单词进行迭代。因为awk默认会逐行执行{}块中的语句,就不需要编写循环了。借助关联数组,当执行count[$0]++时,单词计数就增加。最后,在END{}语句块中通过迭代所有的单词,就能打印出单词及他们各自出现的次数。