Wednesday, May 29, 2019

How to Remove Empty Lines from File in linux?

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 second 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 ( 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

No comments:

Post a Comment