vi Editor: Commands: Advanced Commands To help you learn vi a little better, here are some command sequences that will do powerful things in vi.

Piping part of the text buffer through a command

Let's say you want to convert some 10 lines of the file you are working on to upper-case (starting at the current cursor position); all upper-case. You could do this in the vi Visual state:
     10!!tr 'a-z' 'A-Z'
Another example: let's say you needed to sort a file alphabetically. You can use this sequence in vi to pipe the whole file to sort(1) and back again.
     1G!Gsort -df

Pattern matching and replacement

The general pattern-match-and-replacement capabilities of ex(1) are excellent. They even provide interactive query-replace.

Let's say you need replace the strings 'XMACnnn' where 'nnn' is a number, by 'ZMACROnnn' in almost every place it occurs. You could use this interactive replace to do the job

     :1,$s/XMAC\([0-9]*\)/ZMACRO\1/c
Each time vi finds a candidate for replacement, it will display the line on which was found and you can type "yes" or "no" to replace or not replace.

Macros

vi has a limited macro facility that is part of ex. The macros written using this facility can perform an vi command, but have no parameters and do not nest.

Macros are defined using the :map command. The basic syntax is:

     :map lhs rhs
The lhs should be a single character (such as E or +) and may be a control character if quoted with ^V. Let's define a macro to start up an nroff paragraph. The command character will be P.
     :map P oi.pp^V^[o

Abbreviations

You can define abbreviations with the ex command ab. For instance, to define "ax" as an abbreviation for "AIRX project", you would do this:
     :ab ax AIRX project
Abbreviations are different from macros in that they are expanded in insert state, and they only work when the lhs is a single word (i.e. if ax were part of a longer word it would be left alone).