Linux命令之wc - 統計文件行數、單詞數或字節數

用途說明

wc命令用來打印文件的文本行數、單詞數、字節數等(print the number of newlines, words, and bytes in files)。在Windows的Word中有個“字數統計”的工具,可以幫我們把選中範圍的字數、字符數統計出來。Linux下的wc命令可以實現這個功能。使用vi打開文件的時候,底下的信息也會顯示行數和字節數。

 

常用參數

格式:wc -l <file>

打印指定文件的文本行數。(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)

 

使用示例

示例一

[root@jfht ~]# wc /etc/passwd 
  46   66 2027 /etc/passwd

行數 單詞數 字節數 文件名 
[root@jfht ~]#

[root@jfht ~]# wc -l /etc/passwd 
46 /etc/passwd
[root@jfht ~]# wc -cmlwL /etc/passwd 
  46   66 2027 2027   74 /etc/passwd
[root@jfht ~]# wc -cmlLw /etc/passwd 
  46   66 2027 2027   74 /etc/passwd
[root@jfht ~]# wc -wcmlL /etc/passwd 
  46   66 2027 2027   74 /etc/passwd
[root@jfht ~]#

問題來了:從上面的命令行執行結果來看,wc的輸出數據的順序與的幾個參數的順序好像沒有關係?!

 

示例二 用wc命令怎麼做到只打印統計數字不打印文件名

使用管道線。這在編寫shell腳本時特別有用。

[root@jfht ~]# wc -l /etc/passwd 
46 /etc/passwd
[root@jfht ~]# cat /etc/passwd | wc -l 
46
[root@jfht ~]#

 


示例三 中文編碼的問題

執行環境是中文編碼的。

[root@jfht ~]# echo $LANG 
zh_CN.GB18030

中文編碼文件ehr_object.gv,UTF8編碼的文件ehr_object_utf8.gv。

[root@jfht ~]# file ehr_object.gv ehr_object_utf8.gv 
ehr_object.gv:      ISO-8859 text
ehr_object_utf8.gv: UTF-8 Unicode text
[root@jfht ~]#

[root@jfht ~]# 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 總計
[root@jfht ~]#

 

示例四 中文單詞數的計算

[root@jfht ~]# cat test.txt 
你好Word
Linux

[root@jfht ~]# wc test.txt 
 3  2 16 test.txt

行數 單詞數 字節數 文件名 
[root@jfht ~]#

 

問題思考

1. wc信息的輸出順序問題。

2. UTF8文件的統計問題。

 

相關資料

【1】Computer Hope What's an easy way to get a line count or other stats of a file?
http://www.computerhope.com/issues/ch000820.htm
【2】linux大棚 《wc》-linux命令五分鐘系列之十七
http://roclinux.cn/?p=1288

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