bash 如何只获取文件的行数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18266348/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to only get the number of lines of a file
提问by Shivam Agrawal
How do I get the number of lines of a file in linux?
如何在linux中获取文件的行数?
I only want the number of lines, not the filename.
I want to do it in a single command, without grep or another utility.
我只想要行数,而不是文件名。
我想在一个命令中完成它,没有 grep 或其他实用程序。
wc -l sample.txt
Output
输出
5 sample.txt
Desired Output
期望输出
5
回答by Prashant Kumar
Try this
尝试这个
wc -l < sample.txt
wc
doesn't print out the filename if it reads the file through standard input. The <
feeds the file via standard input.
wc
如果通过标准输入读取文件,则不会打印出文件名。该<
饲料通过标准输入文件。
回答by devnull
Other singlecommands to get the number of lines in a file without filename.
其他单个命令来获取没有文件名的文件中的行数。
sed
:
sed
:
$ sed -n '$=' filename
awk
:
awk
:
$ awk 'END{print NR}' filename
回答by alex
If you want to strip the whitespace out too, use sed
.
如果您也想去除空格,请使用sed
.
wc -l < file | sed 's/ //g'
回答by anubhava
An alternate command to print number of lines without whitespace:
打印没有空格的行数的替代命令:
awk 'END{print NR}' sample.txt
OR using grep:
或使用 grep:
grep -c '^' sample.txt
回答by Yuan He
Try this
尝试这个
cat sample.txt | wc -l
回答by Nathan Mella
If you want to save the output into a variable try this:
如果要将输出保存到变量中,请尝试以下操作:
VAR=$(wc -l < sample.txt); echo ${VAR}
回答by ecagl
you could also do
你也可以这样做
wc -l test.txt | cut -d" " -f1