grep: How to Find Empty Lines in a File

Here is a command to find empty lines in a file in Linux. You might be aware Grep is a popular command (utility) to search words in a file (dataset). With that, you can find empty lines too. Below is the command.

Empty lines mean blank lines. You can use cap (^) and Dollar ($) in grep command to display empty lines in a file.

Here is sample file

I am strini working for srinimf

Here I will show you how to find empty lines
you are nice person

Thanks for reading the srinimf

Here in the above file data, lines 2 and 5 are empty. The same I will get in Ubuntu(Linux).

Do Epic Shit

Do epic shit

Cap with grep command

The purpose of ^ is to get the beginning word. For example, I have a record of Srini coming today.

I will show you how to filter it. Here is the result of how the cap works. It has displayed the record of the first word Srini.

grep with cap

Dollar with grep command

When you use Dollar in the grep command, it displays the last word. See the result. That means the line that ends with the word. See the usage. Useful for interviews also.

grep with dollar

Empty lines: use grep with ^$

For empty lines, you need to use both Dollar and cap. How to use these in grep command, let me show you.

grep -n ^$ filename.txt

The -n displays line numbers. The ^$ filters for empty lines. The input file is filename.txt. Here the line numbers 2 and 6 are empty. So it displayed 2 and 6 in the output.

grep with cap and dollar to find empty lines

Summary

  1. You can do multiple searches using grep command
  2. The ^$ filters and displays empty

Related posts

Author: Srini

Experienced software developer. Skills in Development, Coding, Testing and Debugging. Good Data analytic skills (Data Warehousing and BI). Also skills in Mainframe.