Anybody can google the answer right? Correct. However, not everybody can then apply the solution – especially if it involves editing text files from the command line. Cue The vi Editor.
Before you attempt to modify a file with vi, take a copy of the file so you have something to fall back on when you get it 1. horribly wrong, then 2. subconsciously quit with :wq! subsequently writing your wrongs back to disk. D’oh!
Esc Switch to Command Mode
a Append after cursor
i Insert before cursor
u Undo (maintains history)
x Delete character under cursor
O Open a new line
:set ic turn search case sensitivity off
:set noic turn search case sensitivity on
:set nu turn line numbering on
:set nonu turn off line numbers
Cut, Copy and Paste
dw Cut whole word
dd Cut whole line
cw Change word
4dd Cut four lines
d4w Cut four words
yy Yank (Copy) whole line
y$ Yank from cursor to end of line
y3w Yank three words
3yy Yank three lines
p Paste after cursor
cc Change whole line
c4l Change next 4 chars
c4w Change next 4 words
c$ Change from cursor to end of line
c0 Change from cursor to beginning of line
Searching and Replacing
/word find “word” (forwards)
?word find “word” (backwards)
n goto next match of “word”
N goto previous match of word
:s/dog/cat/gi find and replace all dogs with cats on this line only, ignoring case
:%s /dog/cat/g find dog and replace with with cat on all lines (gl0bally).
:g/mywrod/s//myword/g find ‘mywrod’ and replace it with ‘myword’
:g/matt/s/fooobar/foobar/g find ‘matt’ and replace ‘fooobar’ with ‘foobar’ on those lines.
Saving, Loading and Quitting
Note: hit Esc to enter Command Mode first…
:w save with current filename
:wq save and quit
:q! forcibly quit
:wq! forcibly write and quit
:r <filename> read <filename>
Setting up vi
On UNIX edit the .exrc file in your home dir… smd showmatch ic wrapmargin=0 report=1
If your Linux system uses vim instead of vi, then edit .vimrc, not .exrc to get the same result, though in vim it’s probably already set up nicely to start with.
Add syn on in .vimrc to set syntax highlighting on (nice). Also, set cindent, set autoindent and nu for indentation and line numbering if you want that too.