情景linux--wc -l是用來統計文件行數的嗎?

轉自:https://www.jianshu.com/p/19d97bd9f9d5

情景

在linux,若是但願快速獲得一個文件的行數,我想wc -l必定會被優先想到。那麼,它真的是用來統計文件行數的麼?css

查看以下文件:python

$ cat a.txt

結果:linux

1
2
3

嘗試查看行數:ruby

$ wc -l a.txt
3 a.txt 

如此看來,wc -l能夠統計文件行數。bash

再看另一個例子:測試

$ cat b.txt
1 2 3 4$ 

結果中的$並非b.txt文件的內容,而是b.txt的最後一行沒有換行,因此和linux的命令提示符顯示在了同一行上。ui

嘗試查看行數:spa

$ wc -l b.txt
3 b.txt 

結果倒是3行。code

爲了看清楚兩個文件的內容,使用od -tc命令查看:ci

$ cat a.txt | od -tc 0000000 1 \n 2 \n 3 \n 0000006 
$ cat b.txt | od -tc 0000000 1 \n 2 \n 3 \n 4 0000007 

可見,在b.txt中,數字4後面沒有\n字符。

結論

如今應該弄清楚wc -l命令的含義了吧?

wc -l本來就不是用來查看行數的,而是用來查看文件的newline的數量的。

其實,在wc的man手冊中說的很清楚:

$ man wc
NAME
       wc - print newline, word, and byte counts for each file ... DESCRIPTION Print newline, word, and byte counts for each FILE, and a total line if more than one FILE is specified. With no FILE, or when FILE is -, read standard input. ... -l, --lines print the newline counts 

而在linux系統中,newline字符就是\n字符。

擴展知識

強烈建議親手執行一遍上述命令。

你可能會問,如何作到讓文件的最後一行內容不帶newline字符呢?

使用echo -n便可:

$ man echo 
NAME
       echo - display a line of text ... -n do not output the trailing newline 

echo -n將不輸出尾部的newline字符。

舉例:

$ echo -n "1" > c.txt 
$ cat c.txt | od -tc 0000000 1 0000001 
$ wc -l c.txt 
0 c.txt 

你看,文件中明明有內容,用wc -l獲得的結果倒是0——曾經讓我困惑的真實經歷。

做者:軟件測試技能棧連接:https://www.jianshu.com/p/19d97bd9f9d5來源:簡書簡書著做權歸做者全部,任何形式的轉載都請聯繫做者得到受權並註明出處。

相關文章
相關標籤/搜索