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 "^$"
Related videos on Youtube
Comments
-
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 over 10 yearsOkay. Got it. I dint know that grep ignores newlines between lines. Thanks!!
-
Ed Morton over 10 yearsTo 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 meansthe end of the string
in all tools though. -
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 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 $
andgrep ... ignores the newlines between lines
which I felt could easily be misunderstood. -
Faither almost 3 yearsBe careful, the
-o
grep
option ignores empty lines, it seems. -
Barmar almost 3 years@F8ER GNU grep ignores empty lines, BSD grep doesn't.
-
Faither almost 3 yearsJust to clarify. GNU grep doesn't ignore them without
-o
option and^$
pattern. -
Barmar almost 3 years@F8ER The test I tried was
grep -o '.*'
. GNU grep ignored the empty lines, BSD grep showed them.