How to delete empty lines in a text file in linux/unix

How to delete empty lines in a text file ?

This is similar to how we deleted the text file containing the specified string in the previous article. We can still use the sed command, awk command and grep command to complete this operation.

Let us look at the operation example in detail below.

The following content is the content of the test file, we will use the following content for example demonstration.

hello, this is an example of deleting empty lines in a text file.

Use the sed command to delete empty lines.

Use the awk command to delete empty lines.

Use the grep command to delete empty lines.

Use the awk command to delete empty lines in the file

In the following example, we will use the awk command NF variable to detect the number of fields in the current row. If the number is 0, it means that the current row is an empty line.

➜  ~ awk '{if(NF>0) {print $0}}' text.log

# OR

➜  ~ awk '!/^$/' text.log

You can also use awk ‘NF’ test.log for the same purpose.

Use the sed command to delete empty lines in the file

In the following example, we will use the sed command regular expression to check whether the current line is blank. if the current line is empty, delete the current line.

➜  ~ sed '/^$/d' text.log

Use the grep command to delete empty lines in the file

In the following example, we will use the grep command -v option to exclude matching empty lines, and then use “>” to output the data to a new file.

➜  ~ grep -v '^$' text.log

➜  ~ grep -v '^$' text.log > newFile.log

Add a Comment

Your email address will not be published.