linux的wc -l 命令統計檔案少一行(一般是windows檔案)

來源:互聯網
上載者:User

標籤:二進位   wc   shell   vim   

先簡單介紹

wc(Word Count)命令的功能為統計指定檔案中的位元組數、字數、行數,並將統計結果顯示輸出

格式:wc file

命令參數:

-c 統計Bytes數(位元組數),並顯示檔案名稱

-l 統計行數:使用分行符號‘\n’作為行結束標誌,實際是統計分行符號個數

-m 統計字元數。這個標誌不能與 -c標誌一起使用。

-w 統計字數。一個字被定義為由空白、跳格或換行字元分隔的字串。

-L 列印最長行的長度。

-help 顯示協助資訊

--version 顯示版本資訊

 

執行個體:

wc test.txt

6  24 132test.txt

預設輸出:行,字數,位元組數

 

test.txt內容

Cat test.txt

test1 name1 age1 sex1

test2 name2 age2 sex2

test3 name3 age3 sex3

test4 name4 age4 sex4

test5 name5 age5 sex5

test6 name6 age6 sex6

 

問題:wc 統計行數時少一行:

因為wc –l是按\n作為行結束符統計行數,所以最後一行如果沒有\n的話會統計丟失。

執行個體:比如,在windows下產生同上面test.txt相同的檔案testtt.txt,上傳到linux下:

cat testtt.txt

test1 name1 age1 sex1

test2 name2 age2 sex2

test3 name3 age3 sex3

test4 name4 age4 sex4

test5 name5 age5 sex5

test6 name6 age6 sex6[[email protected] lmj]$

可以看出結尾有點奇怪。這是因為檔案末尾無\n,而是直接用了檔案結束符EOF。這樣檔案使用wc統計就會少一行:

wc -l testtt.txt

5 24 136 testtt.txt

使用管道也不行:

cat testtt.txt | wc -l

5

 

為什麼linux下沒有這樣的問題?

         因為vim編輯器會自動在檔案結尾加上\n,在加上檔案結束符EOF。(linux下文字檔主要按處理,所以vim會末行自動加\n)

 

而對windows檔案用dos2unix轉化也不行:

[[email protected] lmj]$ dos2unix testtt.txt

dos2unix: converting file testtt.txt toUNIX format ...

[[email protected] lmj]$ wc testtt.txt

5  24131 testtt.txt

可以看出windows檔案在linux下還是有相容問題的。檔案字數沒變24,byte數少5個是windows下行結束符是斷行符號\r+換行\n。而linux下只是換行\n

Vim二進位可以看到不同,\n顯示為.,檔案結尾沒有

linux的wc -l 命令統計檔案少一行(一般是windows檔案)

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.