bash 如何使用sed计算文件中非空行的数量?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3633557/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 22:34:29  来源:igfitidea点击:

How to count number of non empty lines in a file using sed?

bashshellsed

提问by lidia

how to find how many lines I have in file by sed (need to ignore spaces and empty lines)

如何通过sed查找文件中有多少行(需要忽略空格和空行)

for example

例如

if I have file with 139 lines (line can include only one character) then sed should return 139

如果我有 139 行的文件(行只能包含一个字符),那么 sed 应该返回 139

lidia

莉迪亚

回答by Gilles 'SO- stop being evil'

This is a job for grep, not sed:

这是一份工作grep,而不是sed

<myfile grep -c '[^[:space:]]'

回答by codaddict

You can try:

你可以试试:

sed -n '/[^[:space:]]/p' filename | wc -l

Here sedprints only those line that have at least one non-space char and wccounts those lines.

这里sed只打印那些至少有一个非空格字符的行并wc计算这些行。

回答by ghostdog74

Use nawk instead of sed.

使用 nawk 而不是 sed。

nawk 'NF{c++}END{print "total: "c}' file

回答by dheerosaur

sed '/^ *$/ d' filename | wc -l

Here, sedprints the lines after deleting all the lines with 0 or more spaces from beginning to the end. wc -lis to count the number of these lines.

这里,sed在删除所有从头到尾有 0 个或多个空格的行后打印这些行。wc -l就是计算这些行的数量。

回答by Majid Azimi

Using Perl one-liner:

使用 Perl 单行:

perl -lne '$count++ if /\S/; END { print int $count }' input.file