Linux 命令行有很多的樂趣,我們可以很容易並且完善地執行很多繁瑣的任務。比如,我們計算一個文本文件中字和字符的出現頻率,這就是我們打算在這篇文章中講到的。
立刻來到我們腦海的命令,計算字和字符在一個文本文件中出現頻率的 Linux 命令是 wc 命令。
在使用的腳本來分析文本文件之前,我們必須有一個文本文件。為了保持一致性,我們將創建一個文本文件,man命令的輸出如下所述。
- $ man man > man.txt
以上命令是將man命令的使用方式導入到man.txt文件裡。
我們希望能得到最平常的單詞,對之前我們新建的文件執行如下腳本。
- $ cat man.txt | tr ' ''\012'| tr '[:upper:]''[:lower:]'| tr -d '[:punct:]'| grep -v '[^a-z]'| sort | uniq -c | sort -rn | head
Sample Output
- 7557
- 262 the
- 163 to
- 112is
- 112 a
- 78 of
- 78 manual
- 76and
- 64if
- 63 be
上面的腳本,輸出了最常使用的十個單詞。
如何看單個的字母呢?那就用如下的命令。
- $ echo 'tecmint team'| fold -w1
Sample Output
- t
- e
- c
- m
- i
- n
- t
- t
- e
- a
- m
注: -w1只是設定了長度
現在我們將從那個文本文件中掰下來的每一個字母,對結果進行排序,得到所需的輸出頻率的十個最常見的字符。
- $ fold -w1 < man.txt | sort | uniq -c | sort -rn | head
Sample Output
- 8579
- 2413 e
- 1987 a
- 1875 t
- 1644 i
- 1553 n
- 1522 o
- 1514 s
- 1224 r
- 1021 l
如何區分大小寫呢?之前我們都是忽略大小寫的。所以,用如下命令。
- $ fold -w1 < man.txt | sort | tr '[:lower:]''[:upper:]'| uniq -c | sort -rn | head -20
Sample Output
- 11636
- 2504 E
- 2079 A
- 2005 T
- 1729 I
- 1645 N
- 1632 S
- 1580 o
- 1269 R
- 1055 L
- 836 H
- 791 P
- 766 D
- 753 C
- 725 M
- 690 U
- 605 F
- 504 G
- 352 Y
- 344.
請檢查上面的輸出,標點符號居然包括在內。讓我們干掉他,用tr 命令。GO:
- $ fold -w1 < man.txt | tr '[:lower:]''[:upper:]'| sort | tr -d '[:punct:]'| uniq -c | sort -rn | head -20
Sample Output
- 11636
- 2504 E
- 2079 A
- 2005 T
- 1729 I
- 1645 N
- 1632 S
- 1580 O
- 1550
- 1269 R
- 1055 L
- 836 H
- 791 P
- 766 D
- 753 C
- 725 M
- 690 U
- 605 F
- 504 G
- 352 Y
現在,我們有了三個文本,那就讓我們用如下命令查看結果吧。
- $ cat *.txt | fold -w1 | tr '[:lower:]''[:upper:]'| sort | tr -d '[:punct:]'| uniq -c | sort -rn | head -8
Sample Output
- 11636
- 2504 E
- 2079 A
- 2005 T
- 1729 I
- 1645 N
- 1632 S
- 1580 O
下一步我們將會生成那些罕見的至少十個字母長的單詞。以下是簡單的腳本:
- $ cat man.txt | tr '''\012'| tr '[:upper:]''[:lower:]'| tr -d '[:punct:]'| tr -d '[0-9]'| sort | uniq -c | sort -n | grep -E '..................'| head
Sample Output
- 1──────────────────────────────────────────
- 1 a all
- 1 abc any or all arguments within are optional
- 1 able see setlocale for precise details
- 1 ab options delimited by cannot be used together
- 1 achieved byusing the less environment variable
- 1 a child process returned a nonzero exit status
- 1 act asifthis option was supplied using the name as a filename
- 1 activate local mode format and display local manual files
- 1 acute accent
注: 上面的.越來越多,其實,我們可以使用.{10} 得到同樣的效果。
這些簡單的腳本,讓我們知道最頻繁出現的單詞和英語中的字符。
現在結束了。下次我會在這裡講到另一個有趣的話題,你應該會喜歡讀。還有別忘了向我們提供您的寶貴意見。