Thursday, May 04, 2006

Regular Expressions : Removing blank lines of a file in vi

In this post, I'm going to show you how blank lines of a file can be removed in vi editor with Regular Expressions.

Following is an ex editor command.

:1,$g/^$/d

Notes :
  • ex editor commands start with a colon.
  • 1,$ stands for first line to last line of the file
  • g for global (look for the pattern following everywhere; do not stop after the first match)
  • pattern to look for is placed inside two slashes (//)
  • ^ is for start of line and $ for end of line. Here, there's nothing between the two so the pattern is used for an empty line
  • d in the end is the command to delete matching lines.
This regular expression does not match a line if it contains spaces. If you want to remove those lines as well, here's the modified command.

:1,$g/^ *$/d

Note that there's an asterisk (*) after a space. An asterisk matches the character preceeding it zero or more times.
e.g.

/a*/ matches a,aa,aaa,any number of times.
/\d*/ mathes an integer. \d is for a digit.

No comments: