Match empty lines in a file with 'grep'

47,766

Solution 1

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

Solution 2

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

Share:
47,766

Related videos on Youtube

Bhargav Ponnapalli
Author by

Bhargav Ponnapalli

I code, I play and I sleep a lot!

Updated on July 12, 2021

Comments

  • Bhargav Ponnapalli
    Bhargav Ponnapalli almost 3 years

    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.

  • Bhargav Ponnapalli
    Bhargav Ponnapalli over 10 years
    Okay. Got it. I dint know that grep ignores newlines between lines. Thanks!!
  • Ed Morton
    Ed Morton over 10 years
    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.
  • Barmar
    Barmar over 10 years
    @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.
  • Ed Morton
    Ed Morton over 10 years
    @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.
  • Faither
    Faither almost 3 years
    Be careful, the -o grep option ignores empty lines, it seems.
  • Barmar
    Barmar almost 3 years
    @F8ER GNU grep ignores empty lines, BSD grep doesn't.
  • Faither
    Faither almost 3 years
    Just to clarify. GNU grep doesn't ignore them without -o option and ^$ pattern.
  • Barmar
    Barmar almost 3 years
    @F8ER The test I tried was grep -o '.*'. GNU grep ignored the empty lines, BSD grep showed them.