Some time we need to remove empty lines from a file. Its can be done manually if file have few lines but if file have thousands of line this is hard to be done manually. Use one of following method to remove empty lines from a file.

Method 1 – Using sed

Sed is an stream editor. We can easily remove all blank lines using sed command. Use one of following sed command to remove blank lines from file. For example main.txt is your original file from which you need to remove blank lines.

Below command will remove all blank line and save content in seconf file out.txt. It will not affect the original file.

# sed '/^$/d' main.txt > out.txt

Now if you want to make changes in original file using -i switch sed command.

# sed -i '/^$/d' main.txt

"-i" option edit files in place, used for make changes in same file.

Method 2 – Using perl

Instead of sed, you can also use perl (a programming languege) to remove blank lines. Use the below example command to remove blank lines from main.txt file.

# perl -i -n -e "print if /S/" main.txt

Method 3 – Using awk

Also you can use AWK command line tool to remove blank lines from a file. For example use below command.

# awk 'NF > 0' main.txt > out.txt