Skip to main content

Execute command when matches a pattern in vim

Sanjeev Kumar Jaiswal's picture

There are some situations while working in vim to add/delete/replace some keywords/lines based on matched pattern. Like remove ^M from a file and we explained various methods to do so.
User may face few other situations where they can use vim commands like %s or :g efficiently.

  1. Find a pattern globally and delete the matched lines
    Ex: Delete all lines which matches “No match” in a file
  1. :%s/pattern//g

Or 
  1. :g/No match/d

 
  1. Delete all blank lines from a file
  1. :g/^$/d

  1. Delete lines which have one or more spaces only
  1. :g /^\s*$/d

or
  1. :g!/\S/d or v/\S/d

  1. Delete all lines which doesn’t match the pattern
    Delete all lines except lines which have the ‘2013-10-29’ date format in the line
  1. :g!/pattern/d
or
  1. :v/2013-10-29/d

  1. Copy all lines matching a pattern to end of file.
  1. :g/pattern/t$

  1. Move all lines matching a pattern to end/top of file.
  1. :g/pattern/m$
or
  1. :g/pattern/m0

 
Source:  http://vim.wikia.com/wiki/Power_of_g
I hope it will solve another vim users problem in their day-to-day activities.

Post new comment

The content of this field is kept private and will not be shown publicly.
CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
Image CAPTCHA
Enter the characters shown in the image.