在linuxlinux中文乱码,假如希望快速得到一个文件的行数,我想wc-l一定会被优先想到。这么,它真的是拿来统计文件行数的么?
查看如下文件:
$ cat a.txt
结果:
1
2
3
尝试查看行数:
$ wc -l a.txt
3 a.txt
这么看来linux定时器,wc-l可以统计文件行数。
再看另外一个反例:
$ cat b.txt
1
2
3
4$
结果中的$并不是b.txt文件的内容linux统计文件行数,而是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字符。
扩充知识
强烈建议亲手执行一遍上述命令。
你可能会问linux统计文件行数,怎么做到让文件的最后一行内容不带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——曾经让我苦恼的真实经历。