Skip to content
Home » Shell Script » 3 Ways to Remove Blank Lines on Linux

3 Ways to Remove Blank Lines on Linux

In this post, I will introduce 3 ways to remove blank lines in files. Let's see the original file in this example first.
[root@localhost ~]$ cat -n temp.txt
     1  Database Administration.
     2
     3  Web Development.
     4
     5
     6  IT Architecture Design.
     7
     8
     9
    10  Project Management.
    11
    12
    13
    14

There're many blank lines in the file temp.txt. Here are the methods to remove them.
  1. Squeeze repeated new line characters into one new line character by tr.
  2. [root@localhost ~]$ cat temp.txt | tr -s 'n'
    Database Administration.
    Web Development.
    IT Architecture Design.
    Project Management.

  3. Delete empty lines by sed.
  4. [root@localhost ~]$ cat temp.txt | sed '/^$/d'
    Database Administration.
    Web Development.
    IT Architecture Design.
    Project Management.

  5. Select non-blank lines by grep or egrep.
  6. [root@localhost ~]$ grep -v '^$' temp.txt
    Database Administration.
    Web Development.
    IT Architecture Design.
    Project Management.

Leave a Reply

Your email address will not be published. Required fields are marked *