How to remove blank lines in a file in Linux

0 22

Blank lines are not always desirable, and you might feel the need to leave them out and only remain with the lines that contain text. Linux offers a couple of text manipulation expressions that you can use to omit or remove blank lines. Let’s explore some of the command-line tools you can use to remove blank lines in a text file.

I have used CentOS 8 for demonstration purposes.

Delete blank lines using the grep command

Grep is one of the most powerful and versatile tools that can help you remove the unwanted empty lines in your text files. Usually, the command is used for probing strings or patterns of characters in a text file, but as you will shortly see, it can also help you get rid of unwanted empty lines

When used with the -v option, the grep command helps to remove blank lines. Below is a sample text file, sample.txt, with alternative non-empty and empty lines.

To remove or delete all the empty lines in the sample text file, use the grep command as shown.

$ grep -v ‘^[[:space:]]*$’ sample.txt

Additionally, you can use the following syntax.

$ grep -v ‘^$’ sample.txt

Moreover, you can save or redirect the output on a different file using the greater than operator ( > ), for instance.

$ grep -v ‘^$’ sample.txt > output.txt

Delete blank lines using the sed command

Shortened as Stream editor, the Linux sed command is a popular tool that performs a vast array of functions including replacing and substituting strings in a file.

Moreover, you can also use sed to remove blank lines in a file as demonstrated below.

$ sed/^$/d’ sample.txt

Delete blank lines using the awk command

Lastly, we have the awk command. This is another command-line tool for tet manipulation that can also get rid of blank lines. To remove an empty file using awk, invoke the command below.

$ awk{if(NF>0) {print $0}}’ sample.txt


We have provided 3 ways that can be useful in removing blank lines in text files. Any other ideas on how to delete those unwanted blank lines? Feel free to get in touch with us in the comment section.

Leave A Reply

Your email address will not be published.

For security, use of Google's reCAPTCHA service is required which is subject to the Google Privacy Policy and Terms of Use.

I agree to these terms.