An example of using regexp in vi

This is from an email on the K12LTSP list. It was submitted as a way of adding several hundred users to a system, using names from a file. There are lots of ways to accomplish this. I've saved this here more for the explanation of the regexp used and the vi commands.

If you spend an hour or two learning stupid vi tricks (mostly regexp substitutions), you'll be able to make those transformations interactively in the editor at the drop of a hat for the rest of your life.

For example, if you have a list like:
the vi command
Will turn it into
and if you get it wrong, just hit 'u' to undo the change.

For the regexp challenged:
: = start an ex (command line mode) command in vi
% = shorthand for 1,$ in the range for the command
(i.e. the whole buffer from the first to last line)
s = substitute
/ = start 'match' portion
\( = start a grouping
^ = anchor to beginning of line
. = any character
* = any number of the previous
\) = end grouping
, = literal match outside groupings
\(.\) = grouping that matches any one character
\(.*\) = grouping that picks up the rest
/ = start 'replace' portion
\1 = what the first grouping matched
, = literal text
\2 = 2nd grouping (the one character)
\3 = 3rd grouping
\L = lowercase following
\1\2 = 1st and 2nd groups again.
/ = end replacement

One problem with complicated ex commands is that while you can undo the operation on the buffer, you can't easily recall and edit the command line itself. I usually either open another window and cut/paste to save, edit, and re-use it or type the command as a normal line in the editor and use vi's delete-to-register, execute-register, put-register commands to save and restore it. For example, with the cursor on the line with the :command typing "add will delete it to the "a" register. Typing @a will execute it. If you don't like it, u will undo the edit and "ap will put the line back in the editor.

--- Les Mikesell