Operate on every line

4.7
(56)

Vim’s :norm command allows you to execute normal mode operations from the command line. By combining with %, we can run a sequence of operations on an entire file:

  • :%norm – Run a normal mode command on the entire file.

For example, let’s suppose we have a list words. We want those words to become keys in a JSON file with empty values ready to provide translations for a specific locale.

Given a single word on a single line, here’s how I would transform that into a JSON key with an empty value string.

  • csw" – Using the Surround plugin, add a quote around the word. A mnemonic is Change Surrounding Word
  • A: "", – Enter insert mode at the end of the line, and insert : "",

If I have a whole file of words, I run that command on the entire file like so:

:%norm csw"A: "", 

There’s a video of this whole sequence at the bottom. Watch how fast we transform the entire file. Now all we need to do is add the { } at the top and bottom and we’ve got a JSON file ready to go. This pattern can work with any sequence of normal mode commands you’d run on a line in Vim.

How useful was this tip?

Average rating 4.7 / 5. Vote count: 56

No votes so far! Be the first to rate this tip.

We are sorry that this post was not useful for you!

Let us improve this post!

Tell us how we can improve this post?

Written by

Colin Bartlett

81 Posts

Vim enthusiast and software developer for more than 20 years.
View all posts

Leave a reply

Your email address will not be published. Required fields are marked *