How do you delete empty lines using ‘sed’?

I was busy with my work today when all of a sudden my colleague interrupted me to enquire how to delete empty lines in a file in Linux. I answered his requirement and thought of creating this post hoping that it would be helpful to others who may be in need of similar requirement.

There are multiple ways to delete empty lines in a file in Linux. Today, we will consider using ‘sed’ for this purpose.

SED is an acronym for Stream Editor. It’s a Swiss army knife for performing basic text transformations on a stream of input. The below command would delete all empty lines from the input.

sed ‘/^$/d’ <input-file-name>

Example:

sed ‘/^$/d’ file_with_empty_lines.txt

The output of the ‘sed’ command is by default dumped on the output console. If you expect ‘sed’ to overwrite the contents of the file with transformed output, then the in-place edit option of ‘sed’ comes to rescue.

sed –i ‘/^$/d’ file_with_empty_lines.txt

In-case you prefer to backup the original file before replacing its contents with the transformed output of ‘sed’, specify a file extension following the ‘-i’ option.

sed –ibak ‘/^$/d’ file_with_empty_lines.txt

In general, to delete all the occurrences of a specific work from a file or an input stream, use ‘sed’ as below.

sed –i ‘/Linux/d’ file.txt


Resources:

Advertisements

One thought on “How do you delete empty lines using ‘sed’?

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s