22

I have a repetitive configuration file and I'd like to match a regex and delete a range of lines before, and after a match. I'd also like delete the match in one command.

I can use...

:g/match/-1d

...several times to delete more than one line from before a match...

...and combine it with a few calls to...

:g/match/+1d

...to delete more than one line after the match...

But is there any way to delete a range of lines, before, after and including, the match with one command?

1 Answer 1

34

You're almost there; you can also specify a range of lines, which is in the form of [line1],[line2][command], instead of just [line][command] (like you're using now).

You can use . to refer to the current line.

  • For the current & next line: :g/match/.,+1d
  • For the current & previous line: :g/match/-1,.d
  • For the previous, current, and next line: :g/match/-1,+1d

See :help [range] for more information, and in this answer there are a few more examples.

3
  • Is the syntax the same in sed?
    – leeand00
    Commented May 27, 2015 at 14:27
  • 3
    @leeand00 No. All that :g does is run an ex command on the lines that match a pattern. So typing :g/match/.,+1d would be exactly the same as going to all lines with match, and typing :.,+1d Commented May 27, 2015 at 14:29
  • This is the coolest thing I've learned on vim in a while. Thanks for sharing!
    – lps
    Commented Aug 30, 2018 at 22:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.