linux 統計文件中單詞出現次數

[請教]統計文件a.txt中“每個單詞”的重複出現次數?若該文件大到幾個G又該如何處理?

方案一:

#!/bin/sh  
#定義源文件和臨時文件  
srcfile=word.txt  
tempfile_words=tempfile_words  
tempfile_words_uniq=tempfile_words_uniq  
 
#取出所有單詞,存入臨時文件$tempfile_words,一行一個單詞  
#去除$tempfile_words中重複單詞,並把換行符替換爲空格,存入臨時文件$tempfile_words_uniq  
tr "[\015]" "[\n]"<$srcfile|sed 's/[^0-9a-zA-Z ]*\([0-9a-zA-Z]*\)[^0-9a-zA-Z]*/\1\n/g'|sed '/^$/d'>$tempfile_words  
sort $tempfile_words|uniq|tr "[\n]" "[ ]">$tempfile_words_uniq  
 
#遍歷所有單詞,統計數目  
words=$(cat $tempfile_words_uniq)  
for word in $words  
do  
    word_num=$(grep $word $tempfile_words|wc -l)  
    echo $word $word_num  
done  


方案二:

tr -s "\t| " "\n" < filename | sort | uniq -c | sort -n -k 1 -r

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章