How to remove blank lines in a file in Linux

Blank lines are not always desirable, and you may feel the need to remove them and leave only those lines that contain text. Linux offers several text manipulation expressions that you can use to omit or remove blank lines. Let’s take a look at some command line tools that you can use to remove blank lines in a text file.

We used CentOS 8 for demonstration purposes.

Remove blank lines with grep command

Grep is one of the most powerful and versatile tools that can help you remove unnecessary blank lines in your text files. Typically, the grep command is used to check lines or character patterns in a text file, but as you will see shortly, it can also help you get rid of unwanted blank lines.

When used with the -v option, the grep command helps remove blank lines. Below is a sample text file sample.txt with alternate nonblank and blank lines.

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

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

Alternatively, you can use the following syntax.

$ grep -v ‘^$’ sample.txt

Moreover, you can save or redirect the output to another file using, for example, the greater than operator (>).

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

Remove blank lines with sed command

Abbreviated as a stream editor, the Linux sed command is a popular tool that performs a wide variety of functions, including replacing lines in a file.

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

$ sed ‘/^$/d’ sample.txt

Remove blank lines with awk command

Finally, we have the awk command. This is another command line tool for managing text messages that can get rid of blank lines as well. To delete empty file using awk run below command.

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

Conclusion

We have provided 3 methods that can be useful for removing blank lines in text files. Are there any other ideas on how to remove these unnecessary blank lines? Feel free to contact us in the comments section.

Related Posts