在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来源:简书简书著做权归做者全部,任何形式的转载都请联系做者得到受权并注明出处。