There are multiple ways of deleting blank lines from a file. This article tells how to use “grep” command to achieve the objective. The “grep” command provides an option “-v” to invert the matching. That means grep finds the lines that are not matching the pattern specified. The matching pattern is a simple regular expression to match all blank lines i.e “^$“. The “^” character means beginning of a line and “$” means end of a line. The pattern matches all blank lines as there are no characters between “^” and “$” characters.

Here is the sample file “sample.txt” that contains three blank lines.

[neo@techpulp ~]# ls
rmblank.sh  sample.txt
[neo@techpulp ~]# cat sample.txt
line 1

line 3

line 5

[neo@techpulp ~]#

The following is the script “rmblank.sh” that takes name of a file as command line argument and removes all blank lines in it. While doing so, it keeps the original file with .original file extension.

[neo@techpulp ~]# cat rmblank.sh
#!/bin/bash

if [ "$1" == "" ]; then
echo "Usage: $0 file"
exit 1
fi

if [ ! -f $1 ]; then
echo "$1: no such file found"
exit 1
fi

mv $1 $1.original || exit 1
grep -v '^$' $1.original > $1
echo blank lines removed from $1 and original file is renamed to $1.original
exit 0
[neo@techpulp ~]#

Let us run the script on “sample.txt” file.

[neo@techpulp ~]# ls
rmblank.sh  sample.txt
[neo@techpulp ~]# ./rmblank.sh sample.txt
blank lines removed from sample.txt and original file is renamed to sample.txt.original
[neo@techpulp ~]# ls
rmblank.sh  sample.txt  sample.txt.original
[neo@techpulp ~]# cat sample.txt
line 1
line 3
line 5
[neo@techpulp ~]#

In the above sample script, you can change the matching pattern from “^$” to any other pattern to achieve objectives like following:

  • remove all lines matching a specific word/string
  • remove all lines which are empty (blank or containing only space and TAB characters)