我只想获取文件中的行数:所以我这样做:
$wc -l countlines.py
9 countlines.py
我不想要文件名,所以我尝试了
$wc -l countlines.py | cut -d ' ' -f1
但这只是回显空行。
我只想9
打印数字
wc
使用标准输入,打印文件名不会有问题
wc -l < countlines.py
如果您的文件没有以\n
(新行)结尾,wc -l
则会给出错误的结果。尝试下一个模拟示例:
echo "line1" > testfile #correct line with a \n at the end
echo -n "line2" >> testfile #added another line - but without the \n
这
$ wc -l < testfile
1
返回1。(wc
计算文件中换行符 ( \n
) 的数量。)
因此,要计算\n
文件中的行数(而不是字符数),您应该使用
grep -c '' testfile
例如,在文件中查找空字符(每一行都是如此)并计算出现次数-c
。对于上面testfile
它返回正确的2。
此外,如果您想计算非空行,您可以使用
grep -c '.' file
不要相信wc
:)
ps:最奇怪的用法之一wc
是
grep 'pattern' file | wc -l
代替
grep -c 'pattern' file
通过管道将文件名wc
从输出中删除,然后tr
删除空格:
wc -l <countlines.py |tr -d ' '
作为替代方案,如果文件名是从标准输入通过管道输入的,则 wc 不会打印文件名
$ cat countlines.py | wc -l
9
另一种方式:
cnt=$(wc -l < countlines.py )
echo "total is $cnt "
像这样使用 awk:
wc -l countlines.py | awk {'print $1'}