我如何计算文本文件中有多少行。例如:
command file.txt
Run Code Online (Sandbox Code Playgroud)
请注意,我只想计算非空行(不计算空格和制表符的行)?。
hee*_*ayl 12
尝试sed
:
sed '/^$/d' file.txt | wc -l
Run Code Online (Sandbox Code Playgroud)
如果您有任何仅包含空格或制表符的行,并且您想从计数中忽略它们:
sed '/^[[:blank:]]*$/d' file.txt | wc -l
Run Code Online (Sandbox Code Playgroud)
amr*_*mrx 11
上面的答案是正确的,但略有不同,您可以使用grep
to 来获得更简单的代码,例如grep -vc '^$' file.txt
例如(A):file.txt
$grep -vc '^$' file.txt
1 First line #This is two tabs to comment.
2
4
3 Fourth line #Another two tabs to comment.
$2
Run Code Online (Sandbox Code Playgroud)
例如(B):file.txt
$sed '/^$/d' file.txt | wc -l
1 First line #This is two tabs to comment.
2
4
3 Fourth line #Another two tabs to comment.
$4
Run Code Online (Sandbox Code Playgroud)
注意结果是 4!当我们只想期待两个时。但这也会计算内容和评论之间的标签。
请注意从 0 开始的计数和从 1 开始的计数与 grep 到 sed 的不同,因为我记得要了解更多详细信息,请搜索 grep 或 sed。