How to delete empty lines using sed command under Linux / UNIX

d

ADVERTISEMENTS



Sed Delete Empty Line Syntax

I need to delete all empty lines but could not figure out sed command for the same. How do I delete all empty lines with sed under Linux or Unix-like systems?sed is a stream editor and perfect for this kind of work. You need to usecommand under sed which act as the delete function.

The syntax is as follows to delete empty lines using sed:

sed '/^$/d' <input-file>

echo "LINE" | sed '/^$/d'

echo "$VAR" | sed '/^$/d'

sed '/^[[:space:]]*$/d' input_file

Examples

So to delete all empty lines from a file called /tmp/data.txt, enter:

$ sed '/^$/d' /tmp/data.txt

To store output to another file use redirection operator:

$ sed '/^$/d' /tmp/data.txt > /tmp/output.txt

OR update the file using -i option:

$ sed -i '/^$/d' /tmp/data.txt

Removing all whitespace only using sed

Consider the following file:

more /tmp/data.txt

Sample outputs:

This is a test foo bar nixCraft Linux and Unix

To delete all empty lines, run:

sed '/^[[:space:]]*$/d' input.file

sed -i '/^[[:space:]]*$/d' input.file

sed -r '/^\s*$/d' input.file > output.file

sed -i '/^[[:space:]]*$/d' /tmp/data.txt

Verify with the help of cat command:

cat output.file

cat /tmp/data.txt



Deleting a line that matches a pattern

You can also match a word or a pattern to delete. For example

$ cat data.txt

Output:

This is a test Linux rulez Windows sucks Redhat is good server disro

To delete all lines that contain a ‘Windows’ word, enter:

$ sed '/Windows/d' /tmp/data.txt > /tmp/output.data.txt

GNU Sed support -i option to edit files in place:

$ sed -i '/Windows/d' /tmp/data.txt

A note about awk

The awk command offers a much simpler solution as compared to sed command. In this example, remove all empty lines using awk:

awk 'NF' my_input > my_output

cat my_output

Conclusion

In short, use any one of the following sed syntax to remove all empty lines from a text file under Linux, macOS, *BSD and Unix-like systems:

sed '/^[[:space:]]*$/d' input > output

sed '/^\s*$/d' in > out

sed '/^$/d' input > output

sed -n '/^\s*$/!p' in.txt > out.txt

See more sed examples from our page: