Why does
grep -c '^\n' myfile.txt
return 0 when there are empty lines in the file?
If there is an empty line, it starts with a new line, right?
Please correct me if I am wrong.
The regular expression to match the end of the line is $
, not \n
(since grep
works a line at a time, it ignores the newlines between lines).
grep -c '^$' myfile.txt
$
is the RE character to match the end of a string, not the end of a line. grep just happens to treat each line of input as a separate string so with grep each string end ($
) occurs where the line ended but other tools behave differently. $
always means the end of the string
in all tools though.
Sep 2, 2013 at 14:26
The regular expression to match the end of the line is $
and grep ... ignores the newlines between lines
which I felt could easily be misunderstood.
Sep 2, 2013 at 14:40
grep and count empty lines like this:
grep -c "^$" myfile.txt
As \n
is considered end of line you need to use line start and line end "^$"
The other answers with -c
are correct.
If you want to see what number is the empty line in the file:
grep -n '^$' myfile.txt
For example:
grep -n '^$' /usr/share/wordlists/rockyou.txt
4751:
34329:
50383:
99361:
154363:
231236:
562997:
2459758:
14344383:
14344384:
14344385:
(If you want to remove them: sed -i '/^$/d' myfile.txt
)
:)