RetroCode UK

Published Date Mar 27, 2019 Reading Time ~3 minutes RSS Feed Vim Productivity

Vim Tips - Updating Several Lines at Once

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:

  • : this colon simply calls the Vim command prompt.
  • s/ specifies the substitution command. The s may be prefixed by a range, like %s/ for all lines, 1,3s/ for the first three lines, or, if you’re in visual mode then the command will already be prefixed with '<,'>s/ which will work for the current selection.
  • regular_expression/ which is simply a valid regular expression
  • replacement/ is the text to replace any matches with
  • g indicates that you would like to replace all matches for each line

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.