9

If I have a file with a lot of comments in it and I want to delete all of the comments from say, line 3 to the end of the file, what's the best way to do it?

I'm stuck, since what I first tried doesn't seem to do quite what I want:

:3,$/^#/d

Instead of looking for the pattern and deleting lines with it in the range from 3 to the end of the file it deletes all of the lines from 3 to through a line that matches the pattern, and then stops.

So how do I apply an ex command to a range of lines. In this case it's to to the end of a file, but would it be different if I were to do it to a mark, or between lines 10 and 20 or other ranges?

14

Use the :global command for that:

:3,$g/^#/d

You can apply it to lines not matching a pattern:

:3,$g!/^#/d

You can use the full range mechanism with it (see :help :range):

:.,/#define/+3g/^#/d

And you can use it with any command:

:3,$g/^#/s/foo/bar/g

It's one of the most powerful commands in Vim, please see :help :global for details.

  • You could also use :3,$v/foo/d for lines that do not match a pattern. :h vglobal – vappolinario Jun 9 '15 at 19:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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