轉自:https://www.jianshu.com/p/19d97bd9f9d5
情景
在linux,如果希望快速得到一個文件的行數,我想wc -l
一定會被優先想到。那么,它真的是用來統計文件行數的么?
查看如下文件:
$ cat a.txt
結果:
1
2
3
嘗試查看行數:
$ wc -l a.txt
3 a.txt
如此看來,wc -l
可以統計文件行數。
再看另外一個例子:
$ cat b.txt
1 2 3 4$
結果中的$
並不是b.txt文件的內容,而是b.txt的最后一行沒有換行,所以和linux的命令提示符顯示在了同一行上。
嘗試查看行數:
$ wc -l b.txt
3 b.txt
結果卻是3行。
為了看清楚兩個文件的內容,使用od -tc
命令查看:
$ 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
來源:簡書
簡書著作權歸作者所有,任何形式的轉載都請聯系作者獲得授權並注明出處。