Execute command when matches a pattern in vim

User Rating: 5.0 (1 votes)
Sending

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

[vim]:%s/pattern//g
[/vim]
Or 
[vim]:g/No match/d
[/vim]
 

  1. Delete all blank lines from a file

[vim]:g/^$/d
[/vim]

  1. Delete lines which have one or more spaces only

[vim]:g /^\s*$/d
[/vim]
or
[vim]:g!/\S/d or v/\S/d
[/vim]

  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

[vim]:g!/pattern/d
[/vim] or
[vim]:v/2013-10-29/d
[/vim]

  1. Copy all lines matching a pattern to end of file.

[vim]:g/pattern/t$
[/vim]

  1. Move all lines matching a pattern to end/top of file.

[vim]:g/pattern/m$
[/vim] or
[vim]:g/pattern/m0
[/vim]
 
Source:  http://vim.wikia.com/wiki/Power_of_g
I hope it will solve another vim users problem in their day-to-day activities.

Follow Me

Sanjeev Jaiswal

Co-Founder at Alien Coders
He loves web programming and security and co-founder of Alien Coders. He usually shares and helps engineering students and IT professionals in academics and jobs.

An avid reader and quick learner.
Follow Me

FB Comments

comments

Leave a Reply


7 + = eleven

  Home