Tuesday, May 29, 2007

VIM Crash Course. Study #1.

VIM (or equally VI) crash course #1: Correcting misspelled word AAA to BBB in a file "file-name".

Most frustrating part in starting with vim (or vi) is that one often is forced to work with vim while there is no other editor on the system. That happens alot when working on some embedded system or antique unique boxes, which do have slimest and featureless editor installed. E.g. busybox or original vi from Bill Joy. To be frank, I'm also frustrated with the both things. But still they are cheap and thus are widespread. Making some use of them is only natural.

Here we go.

Launching: vi file-name

Commands needs to be typed as they a written here (without line numbers of course).

1. /AAA<Return>

2. n

3. :s/AAA/BBB/<Return>

4. :wq<Return>


1. '/' is search operator. Whatever you would type after it is search string. Search string is terminated (and search started) by pressing Enter. That will move cursor to place of first match. Or complain that string isn't found.

2. Optional step, if found match isn't what you want to replace. 'n' repeats last search and moves cursor to next match in file. Press 'n' repeatedly, until you have found what you want to replace. With 'n' you can go over all matches in file and after hitting end of file, vim would restart search from the beginning of file.

3. ':' colon is start of many commands in vim. 's' is short for "substitute" command. Its syntax is simple. 's' is followed by '/'. After first slash goes string you want to be replaced (or substituted). It is terminated by second '/'. After second slash goes replacement string. It is also optionally terminated by '/'. Pressing Enter would execute the substitution operation on current line, replacing first entry of AAA with BBB.

4. ':wq' is vim's command to "write and quit". That would write modified file and leave vim.

Notice, that the editing was done without switching into vi's infamous insert mode. The example doesn't use any kind of complex keys and guaranteed to work on all terminals.

No comments: