[root@test88 ~]# vim word_freq.sh
#!/bin/bash
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@test88 ~]# sh word_freq.sh test.txt
Word Count
test 1
oldboy 1
liyong 1
#egrep -o 表示只打印匹配到的字符,由換行符分割
#\b是正則表達式里的單詞邊界符,位於能構成單詞的字符(字母數字下划線)和不能構成單詞的字符之間
#比如一段文本:
[root@test88 ~]# vim boundary.txt
peter 2is learning linux.
[root@test88 ~]# egrep -o "[[:alpha:]]+" boundary.txt
peter
is
learning
linux
[root@test88 ~]# egrep -o "\b[[:alpha:]]+\b" boundary.txt
peter
learning #is沒匹配出來
linux
#顯然單詞邊界的作用在於先划定一段區域,從非單詞部分開始到非單詞部分結束,然后看區域內容是否匹配。從而能保證連續的一段內一定全是字母,沒有數字或者下划線。通常寫單詞都是一個單詞空一個,如果單詞內出現數字或下划線就不認為是單詞。如果不加\b實際上匹配的是一串連續字母。
#count是一個關聯數組,count[$0]表示索引為$0的值,當使用count[$0]++的時候,count[$0]的值默認為0的整型,而且這個值是變化的,索引每重復一次,值就加一。