Coding, is? Fun!

Tuesday, November 22, 2005

VI Editor - common commands

I found an excellent reference in Wikipedia for common vi commands. Here is the link:
VI Common tasks

Vi has two modes - Insert and Command mode.
Switching between the modes:
In command mode, typing "i" takes you to Insert mode, where you type in the text you are so interested in editing.
In Insert mode pressing the Escape key takes you to the command mode.
vi opens in command mode by default.

The vi command mode is pretty complex so I am just listing the most common things you may need to do, if you had the misfortune of having nothing other than vi.

1. Opening an existing file called ram.txt:
Type in vi ram.txt
2. Opening the same file in read only mode:
vi -R ram.txt
3. Navigating to the end of the file you just opened. Remember, you are in command mode:
Type in "G" in command mode. It takes you to the end of the file.
Type in 10G to move to line 10.
4. Quitting vi
In command mode, typeing :q! quits without saving your changes
In command mode, typing :wq quits after saving, if an existing file is opened
5. Getting Help
:help brings the help window. Typing :q on it closes the help window.
6. Navigate up and down the file
In command mode, h moves left, j moves down, k moves up and l moves to the right. Note that these keys are adjacent in your keyboard.
7. Copy and Paste
Copy till end of file, type in :yG
To copy a line, type in :y$
To copy till the next occurence of a pattern, say "END" use
:y/END
To paste, type in :p
To cut till end of file, type in :dG

To mark (block a set of lines) and then copy, reach the line where you want to mark and type (in command mode) m such as ma
Now to copy upto the bookmark, type in y' such as y'a. This copies a block of text.

8. To undo, type u
9. To search for a pattern
/END will find next occurence of END.
// will repeat the search.
10. Repeat a command
. (period) is for repeating a command
11. Delete text
dw deletes a word.
d$ deletes till end of line
x deletes current character.


The one thing I have not found is how to search a pattern and replace all occurences of it.
The Linux equivalent of vi is vim. It comes with enhanced features.