How do I insert a new line of text after every line matching a pattern using the global command?
Answer
:g/pattern/put ='text'
Explanation
Combining :global with :put = lets you insert synthesized lines of content after every line matching a pattern — without plugins or complex macros. This is a powerful idiom for bulk document manipulation like inserting separators, blank lines, or formatted text.
How it works
:g/pattern/— run the following command on every line matchingpatternput ='text'— insert the literal string as a new line below the current line- The
=afterputmeans the argument is a Vim expression, so you can use any Vimscript expression
Example
Given a list of section headers:
## Introduction
## Overview
## Conclusion
Running :g/^##/put ='---' inserts a separator after each header:
## Introduction
---
## Overview
---
## Conclusion
---
To insert blank lines after each function definition:
:g/^def /put =''
To insert a dynamic line based on a Vim expression:
:g/^function/put ='// end ' . getline('.')
Tips
- Use
:g/pattern/put! ='text'(with!) to insert above instead of below put =repeat('-', 40)inserts a 40-character divider line- Combine with
:sortor:global/^$/dafterward to clean up empty lines