Tempus
Tempus

Reputation: 240

How to count lines which have only newline character on line?

I want to grep and count lines that only consist from newline character. I tried:

grep -cx '\n' file.txt

but this didn't work for me.

Example of file.txt:

a
bb

c
ddd

wwfs

The result should be 2.

Upvotes: 1

Views: 98

Answers (2)

Chris Seymour
Chris Seymour

Reputation: 85845

You want to count empty line then:

$ grep -c '^$' file
2

Or with no regular expressions needed:

$ fgrep -xc '' file
2

Or with awk:

$ awk '!NF{c++}END{print c}' file
2

Upvotes: 3

hek2mgl
hek2mgl

Reputation: 158080

You might use this:

grep -c '^$' your.file

It matches lines with no content in it (from start ^ to end $) and prints the number of matches (-c)

Upvotes: 2

Related Questions