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


一 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 ~]# 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.UTF-8

中文編碼文件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 test1

你好中國
Linux


[root@jfht ~]# wc test1

2 2 19 test1

行數 單詞數 字節數 文件名稱 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM