Delete all blank lines in a file using vi editor

Introduction

The vi editor (available on all Unix flavors) might not be as powerful as some GUI editors such as Sublime Text however there are situations where it is the only available option. Anyway, vi is indeed a powerful command based text editor specially if we master the supported commands. Let us now answer the main question in this post. How do we delete all empty lines in a file using the vi editor? There are a couple of ways to do that…

Command syntax

  • Hit ESCAPE
  • Type : after which we initiate a vi command
  • Type g which means apply the command globally in the file
  • Type /regular expression to match empty lines/d

The d at the end means delete the matching lines. So the question becomes how to match an empty line. This is a typical regular expressions question. Let us take some examples…

Delete matching lines

Recall that in regular expressions, ^ means begin with and $ means end with. The first example below means match lines that begin and end with zero or more spaces. The second example means match lines that begin and end with zero or more white space characters not necessarily spaces. The third example means match lines that are empty, lines with whitespace are not going to be deleted in this case

Delete non matching lines

Instead of using g we can use v which means apply the command on non matching lines (negation) so in this case we need to match non blank lines in order for the delete operation to remove the blank lines

Thanks for visiting.

Add a Comment

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