Linux Bash Remove Blank Lines

Linux Bash Remove Blank Lines

Removing of blank lines from a file or an output can be tricky and tedious tast. But Linux/bash has the ability to accomplish this using sed or even grep.

We will take an example of a file test.txt, which has a few blank lines. We will use both sed and grep to demonstrate the usage.

Linux Bash Remove Blank Lines – using sed

First let’s see the content of the file test.txt:

[email protected]:~$ cat test.txt 
This is a file

with a lot of


blank lines.



let's try to remove some

Let’s remove the blank lines using sed.

The syntax is

sed ‘/^$/d’ FILE

So in our case it will be:

sed ‘/^$/d’ test.txt

Output:

[email protected]:~$ sed '/^$/d' test.txt
This is a file
with a lot of
blank lines.
let's try to remove some

Linux Bash Remove Blank Lines – using grep

Let’s remove the blank lines using grep

The syntax is

grep -v ‘^$’ FILE

So we will use it like:

grep -v ‘^$’ test.txt

Output:

[email protected]:~$ grep -v '^$' test.txt
This is a file
with a lot of
blank lines.
let's try to remove some

Linux Bash Remove Blank Lines

2 Comments

  • Amit

    March 20, 2013 at 4:32 am Reply

    i have a question.. in manual there is mentioned $ for last line only. how is it removing all blank lines?

    • Gagan

      March 20, 2013 at 6:49 am Reply

      Yes, $ signifies the end of the line. However, ^ indicates the beginning of the line. So here we are searching blank (no character) and ending with blank (no character) ^$

Post a Comment

Time limit is exhausted. Please reload CAPTCHA.