Vi

From Rizzo_Lab
Jump to: navigation, search

vi is a Unix/Linux text editor used for creating and modifying a range of different types of files. Use of vi can be cumbersome at first and requires knowledge of at least 15 or so special commands in order to be useful.

At linux prompt type "vimtutor" (without the quotes) to start a built in tutorial

See vi on Wikipedia for a list of commands.


Insert Mode vs. Normal Mode

i              enter insert mode
<Esc>          enter normal mode

Insert Mode

In insert mode, you can type and delete text just as you would in a word processor. When you are done, press the <Esc> key to go back into normal mode.

Normal Mode

Navigating the file:

<Arrow keys>   move up, down, left, right
0              move to the beginning of a line
$              move to the end of a line
1G             move to the first line of the file
10G            move to the 10th line of the file
G              move to the last line of the file
<ctrl+u>       move up 1/2 a page
<ctrl+d>       move down 1/2 a page

Search for text:

/              After pressing the '/'key, a prompt will show up on the bottom left of the screen. Type in the text you want to match and press 'Return'. 
               Press the 'n' key to go to the next matched result (press the 'N' key to cycle through the results in reverse)

Find and replace text:

:%s/old/new/g  will search through the file and replace every instance of 'old' with 'new', without 'g' this will only replace the first instance of each 'old' per line, add 'c' to confirm each individual change

Delete, copy and paste text:

x              delete a character
dl             delete a letter
dw             delete a word
dd             delete a line
5dd            delete 5 lines
yy             copy a line of text
3yy            copy 3 lines of text
p              paste the last text you copied of deleted

Saving and quitting

:w             save the file
:wq            save the file and quit
:q             quit vi mode
:q!            quit without saving the changes you made to the file

Other useful things to know

u              undo the last change you made
.              repeat the last change you made

Your .vimrc file

Add the following lines to your vi configuration file, ~/.vimrc:

 :set ruler
 :set term=ansi
 :syntax on
 :set number
 :set tabstop=4
 :set shiftwidth=4
 :set expandtab