Suppose I have the file:







How can I use something like the global command to delete every empty line in between 'begin' and 'end'?

:/begin/,/end/ g/^$/d only deletes the space in the first begin/end block.

Thank you for your help!

2 Answers 2


In the very general case, the :g command cannot be called recursively. There is one exception: Since Vim patch 8.0.0630, one can call a recursive :g command, if it operates only within a single line. So you can do something like (quoting the help):

When the command is used recursively, it only works on one line. Giving a range is then not allowed. This is useful to find all lines that match a pattern and do not match another pattern:


This first finds all lines containing "found", but only executes {cmd} when there is no match for "notfound".

However that means, this does not apply to your use case here. You would need to call :g to mark all begin/end regions, and then call another :g command to find empty lines (to be deleted).

However, in your case, you can use the :s command like this:


Note: We are searching for line start (^), followed by a line break (\n), because we want to remove this line break, effectively deleting the empty line. For that reason using the pattern ^$ to the :s command would not work, as it would leave the empty line intact (keep the line break).


You could instead try this: :g/begin/,/end/ s/^$//. I don't think g works recursively, so using s instead seems to do the job.

Your Answer

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

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