一 wc簡單介紹
wc指令用來列印檔案的文本行數、單詞數、位元組數等(print the number of newlines, words, and bytes in files)。在Windows的Word中有個“字數統計”的工具,能夠幫我們把選中範圍的字數、字元數統計出來。Linux下的wc指令能夠實作這個
功能。使用vi打開檔案的時候。底下的資訊也會顯示行數和位元組數。
二 經常使用參數
格式:wc -l
列印指定檔案的文本行數。(l=小寫L)
下面參數可組合使用。
參數:-c, --bytes
列印位元組數(print the byte counts)
參數:-m, --chars
列印字元數(print the character counts)
參數:-l, --lines
列印行數(print the newline counts)
參數:-L, --max-line-length
列印最長行的長度(print the length of the longest line)
參數:-w, --words
列印單詞數(print the word counts)
三 使用示範樣例
示範樣例 一
[[email protected] ~]# wc /etc/passwd
46 66 2027 /etc/passwd
行數 單詞數 位元組數 檔案名稱
[[email protected] ~]# wc -l /etc/passwd
46 /etc/passwd
[[email protected] ~]# wc -cmlwL /etc/passwd
46 66 2027 2027 74 /etc/passwd
[[email protected] ~]# wc -cmlLw /etc/passwd
46 66 2027 2027 74 /etc/passwd
[[email protected] ~]# wc -wcmlL /etc/passwd
46 66 2027 2027 74 /etc/passwd
[[email protected] ~]#
問題來了:從上面的指令行運作結果來看,wc的輸出資料的順序與的幾個參數的順序好像沒有關系?!
示範樣例二 用wc指令怎麼做到僅僅列印統計數字不列印檔案名稱
使用管道線,這在編寫shell腳本時特别實用。
[[email protected] ~]# wc -l /etc/passwd
46 /etc/passwd
[[email protected] ~]# cat /etc/passwd | wc -l
46
[[email protected] ~]#
示範樣例三 中文編碼的問題
運作環境是中文編碼的。
[[email protected] ~]# echo $LANG
zh_CN.UTF-8
中文編碼檔案ehr_object.gv,UTF8編碼的檔案ehr_object_utf8.gv。
[[email protected] ~]# file ehr_object.gv ehr_object_utf8.gv
ehr_object.gv: ISO-8859 text
ehr_object_utf8.gv: UTF-8 Unicode text
[[email protected] ~]#
[[email protected] ~]# wc ehr_object.gv ehr_object_utf8.gv
11 105 830 ehr_object.gv
wc: ehr_object_utf8.gv:4: 無效或不完整的多位元組字元或寬字元
11 105 866 ehr_object_utf8.gv
22 210 1696 總計
[[email protected] ~]#
示範樣例四 中文單詞數的計算
[[email protected] ~]# cat test1
你好中國
Linux
[[email protected] ~]# wc test1
2 2 19 test1
行數 單詞數 位元組數 檔案名稱