31

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.

3 Answers 3

52

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
8
  • Okay. Got it. I dint know that grep ignores newlines between lines. Thanks!! Sep 2, 2013 at 5:30
  • 4
    To be precise, $ 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.
    – Ed Morton
    Sep 2, 2013 at 14:26
  • 1
    @EdMorton In contexts where there can't be multiple lines, EOL and EOS are equivalent. Anything that processes only one line at a time is that context.
    – Barmar
    Sep 2, 2013 at 14:30
  • @Barmar I understand where you're coming from, I was just addressing the statements that 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.
    – Ed Morton
    Sep 2, 2013 at 14:40
  • Be careful, the -o grep option ignores empty lines, it seems.
    – Artfaith
    Jun 10, 2021 at 2:29
10

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 "^$"

0
0

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 )

:)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.