How to Remove All Commented Lines or Lines with a Specific Pattern in vim?

Updated on September 3, 2017

Recently I was doing lot of text editing on one of my server (for maintenance activity) – where I need to optimize the size of a file by removing all that have specific pattern, sometimes all lines commented lines and sometimes all lines that do not contain a specific pattern.

For example, one of my server had plenty of disabled user accounts (commented lines in /etc/passwd file) – where I need to remove all those disabled accounts (commented ones) using vim. Here’s what I did:

Note: You will have to do this in command mode – ESC and :

If you want to remove all commented lines from a file, then you will have to remove the lines starting with ‘#’.

:g/#/d

(or)

:g/^\#/d

Assume, you want to remove all lines that match/contain specific pattern – then the command is similar to the above one. For example:

:g/somepattern/d

If you want to remove all lines that do not contain a specific pattern, lets says leave all commented lines and delete the rest. Lookout for ‘!’ symbol in the below command

:g!/#/d

The above command will delete all the lines that does not start with ‘#’. Alternatively, you can use the below command.

: v/#/d

In the above command, we use ‘v’ instead of ‘g’ and no ‘!’ is required.

Was this article helpful?

Related Articles

Leave a Comment