天天看點

shell統計文本中單詞的出現次數

Ubuntu14.04

給定一個文本,統計其中單詞出現的次數

方法1

# solution 1

grep與awk配合使用,寫成一個sh腳本 fre.sh 

sh fre.sh wordfretest.txt      
#! /bin/bash
# solution 1
if [ $# -eq 0 ]
then
echo "Usage:$0 args error"
exit 0
fi
if [ $# -ge 2 ]
then
echo "analyse the first file $1"
fi

#get the first file
filename=$1
grep -E -o "\b[[:alpha:]]+\b" $filename | awk ' { count[$0]++ } 
END{printf("%-20s%s\n","Word","Count");
for(word in count)
{printf("%-20s%s\n",word,count[word])}
}'      

###########################

# 先判斷輸入是否正确,如果輸入大于1個檔案,用第一個檔案

# 用grep把單詞提取出來,用awk來統計這些單詞;最後列印出來

補充說明:

參數說明:

-eq:等于

-ne:不等于

-le:小于等于

-ge:大于等于

-lt:小于

-gt:大于

 \b     backspace   printf參數

awk說明

awk由内容和動作組成;awk pattern {action}

pattern可以是

BEGIN;  END;  expression;    expression , expression;

可以執行 for ( var in array ) statement

1.BEGIN子產品:這個子產品包括了一個操作塊(也就是"{ }"内的内容)。該操作塊是在檔案輸入之前執行的,

也就是不需要輸入任何檔案資料,也能執行該子產品。

BEGIN子產品常用于設定修改内置變量如(OFS,RS,FS等),為使用者自定義的變量賦初始值或者列印标題資訊等。

BEGIN子產品中的語句操作以“;”标志或者分行隔開。

eg: awk 'BEGIN{print "Hello World! Begin doing!"}' #輸出字元串 

2. END子產品:與BEGIN子產品相反,是處理完檔案後的操作。不比對任何輸入行,常用于輸出一些總結資訊。

比對表達式:

[[:alpha:]]  代表 字母

[[:alnum:]] 代表 字母與數字字元

[a-zA-Z0-9]代表單個字母和數字字元

 grep -E "\b[[:alpha:]]+\b" move.sh 

比對到 move.sh 中所有的單詞

 grep -E -o "\b[[:alpha:]]+\b" move.sh 

把比對到的單詞每行1個列印出來

 "\b[[:alpha:]]+\b" 

能比對到整個單詞

方法2

假設 words.txt 是目标檔案,隻用一行代碼

# solution 2

awk -F' ' '{for(i=1;i<=NF;i=i+1){print $i}}' words.txt |sort|uniq -c|sort -nr|awk -F' ' '{printf("%s %s\n",$2,$1)}'      

通常,awk逐行處理文本。awk每接收檔案的一行,然後執行相應的指令來處理。

用legal檔案來做示例

$ cat /etc/legal 
The programs included with the Ubuntu system are free software;
the exact distribution terms for each program are described in the
individual files in /usr/share/doc/*/copyright.
Ubuntu comes with ABSOLUTELY NO WARRANTY, to the extent permitted by
applicable law.      
# 搜尋統計單詞“law”的個數
$ awk -F : '/law/{count++} END{print "the count is ",count}' /etc/legal
the count is 1
# 統計單詞“the”的個數
$ awk -F : '/the/{count++} END{print "the count is ",count}' /etc/legal 
the count is 3      

找到指定單詞,自定義變量count自增,最後輸出語句和count值

指令sort,把各行按首字母排列順序重新排列起來

sort -nr,每行都以數字開頭,按數字從達到小,排列各行

uniq -c,統計各行出現的次數,并把次數列印在每行前端

awk參數 NF - 浏覽記錄的域的個數

綜合起來,指令就是

awk -F' ' '{for(i=1;i<=NF;i=i+1){print $i}}' /etc/legal |
sort|uniq -c|sort -nr|awk -F' ' '{printf("%s %s\n",$2,$1)}'      

最後的awk調換了單詞和數字的位置

統計 /etc/legal 中單詞出現次數,并以“單詞 次數”格式輸出結果

上一篇: 找單數