"Vim Tips - Updating several lines at once"

vim productivity

Here are a few handy vim tips.

Read all files in a path: :r!ls ~/Pictures/*.jpg, which will put the list of files into your Vim buffer:


There are now a few ways in which you can edit those lines.

Line Substitution s

Using the substitution method you can update each of the lines at the same time. The format of this is :s/regular_expression/replacement/g.

There are a few parts to this command:

Note that this command works on a line-by-line basis.

An example for the above list might be :%s/^\~\/Pictures\/// (note the tilde ~ and forward slash / both need to be escaped, and the ^ indicates the match should start on the beginning of the line) which results in:


Pro Tip: You can skip specifying the regular expression if you have already searched using something like /^... and then you can simply do :%s//replacement

Replacement by matches g

The command :g works in quite a similar way to :s although after the replacement part, you can specify a vim command.

For example, again starting from the text at the top:%g/^\~\/Pictures/norm c5t_amiga-image will result in the following:


In this example norm specifies Normal Mode, in which you can execute a sequence of Vim commands (i.e. j to move left, x to delete a character, etc). So in this example c5t_ means change up until the fifth underscore, and then enter amiga-image in place from the beginning of the line. Additionally %g performs this command sequence for all lines in the current document that match the given regular expression.

Pro Tip: You can add special characters in to the sequence (like escape) by pressing Ctrl-V before the button in question. Escape will then look something like ^[

Normal Mode

In a similar way you can also select lines in question and enter '<,'>norm ... which might be simpler in some instances.


In Vim there are often many ways to accomplish the same thing, but with each trick you can add to your armoury the more it will help with productivity. Honestly, once you're past the initial period of frustration coming to terms with Vim's idiosyncratic nature you'll eventually find yourself working at a blinding pace, and other editors (at least that don't have a good Vim mode) will feel like treacle in comparison.

Published on 2019-03-27