vimtricks.wiki Concise Vim tricks, one at a time.

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 matching pattern
  • put ='text' — insert the literal string as a new line below the current line
  • The = after put means 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 :sort or :global/^$/d afterward to clean up empty lines

Next

How do I highlight all occurrences of a yanked word without typing a search pattern?