Delete Lines Beginning With A Character In Vim

March 22, 2011 by
Filed under: HowTo, linux, Ubuntu, windows 

Lately I've been using Vim quite a bit to edit text files for my work. One of the things I wanted to do recently was to remove all of the comments from a text file in order to reduce its size prior to uploading it to the server over my relatively slow internet connection. In this post I'll show how to remove lines that begin with a given character or character string using vi/Vim/gVim

First I'm going to show how to remove all lines that begin with a "normal" character. Let's say that you want to remove all lines that start with the letter "A". You'll need to be in command mode first to do this.

:g/^A/d

In my case, I wanted to remove all lines that started with a dollar sign: $. This is a special character, so it has to be escaped with a backslash.

:g/^\$/d

If you want to remove the comments from a bash script, then you need to remove all lines that start with a number sign (aka hash): #. This works in a similar fashion to the command above.

Affiliate Link
:g/^\#/d

The last thing I wanted to do to my file was to remove all blank lines. Here you see the dollar sign used with its special meaning.

:g/^$/d

 

Comments

Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>