lidia
lidia

Reputation: 3183

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

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

for example

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

lidia

Upvotes: 6

Views: 10851

Answers (5)

Majid Azimi
Majid Azimi

Reputation: 5745

Using Perl one-liner:

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

Upvotes: 0

dheerosaur
dheerosaur

Reputation: 15172

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

Here, sed prints the lines after deleting all the lines with 0 or more spaces from beginning to the end. wc -l is to count the number of these lines.

Upvotes: 1

This is a job for grep, not sed:

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

Upvotes: 16

ghostdog74
ghostdog74

Reputation: 342373

Use nawk instead of sed.

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

Upvotes: 1

codaddict
codaddict

Reputation: 455062

You can try:

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

Here sed prints only those line that have at least one non-space char and wc counts those lines.

Upvotes: 3

Related Questions