Vim – Running Commands on Matching Lines

Over the years I have used many editors. There was VM/CMS Xedit, Burroughs CANDE, ISPF/PDF editor, the IBM E, E2, E3 series of editors which influenced SlickEdit somewhat. There was a brief foray into PC editors including MultiEdit and the Borland C IDE. On OS X, I have used TextMate, SlickEdit, Sublime and now Vim.

One of the most amazing features in Vim is its command-line mode and bears similarity to that found in ISPF/PDF Editor, Xedit, SlickEdit and E series of editors. Instead of manipulating the content directly, one can issue commands to do the dirty work.

In particular the global command is really useful.

For example. given the poem below, assume that one wants to apply a change on all lines containing the word ‘was’, say uppercase the entire line

  Mary had a little lamb,
  His fleece was white as snow,
  And everywhere that Mary went,
  The lamb was sure to go.

  He followed her to school one day,
  Which was against the rule,
  It made the children laugh and play
  To see a lamb at school.
              

One could enter the following

 :g/\/ norm 0gU$
              

and end up with the following.

  Mary had a little lamb,
  HIS FLEECE WAS WHITE AS SNOW,
  And everywhere that Mary went,
  THE LAMB WAS SURE TO GO.

  He followed her to school one day,
  WHICH WAS AGAINST THE RULE,
  It made the children laugh and play
  To see a lamb at school.
              

Basically this can be read as “For every line that contains the word was (g:/<was>/, execute a series of normal mode commans (norm) i.e. go to the beginning of the line (0) and then upper case to the end of the line (gU$)”.