Page tree

Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

1.Starting vi and dabbling with it

Code Block
languagebash
vi
i  # get into input mode
:a # add text after the cursor 

In input mode, type anything you want.

2.Saving in vi:

Esc

Get out of input mode and into command mode

Code Block
languagebash
:w vi_file_name  # save as a vi file
Enter

If you have saved the file once, just use

Esc
Code Block
languagebash
:w 
Enter

 

3.Exiting vi:

Esc
Code Block
languagebash
:q # quit vi

If you haven't saved your latest changes, vi will not quit and will tell you to use ! to override.

 

Code Block
languagebash
:q! # quit without saving

 

  • We can use  : wq  to save and quit vi.
  • If you want to save a file over an existing file, use  :w!  existingfilename in command mode. The  !  forces vi to overwrite the original.

4.Adding and deleting text

vi

i

type some you want to add.

Esc

Choose a command, based on what you want to do:

Code Block
languagebash
 :a   # Adds text after the cursor
 :A   # Adds test after the current line
 :i   # Inserts text before the cursor
 :I   # Inserts text at the beginning of the current line
 :o   # Inserts a blank line after the current line
 :O   # Inserts a blank line after before the current line

 :x   # Deletes one character under the cursor
 :X   # Deletes one character behind the cursor
 :dd  # Deletes the current line
 :5dd # Deletes five lines from the current line
 :r   # Replaces the character under the cursor
 :R   # Replaces the existing text 

 :y   # Copies the current line
 :p   # Pastes the copied line 
 :u   # Undoes the last change
 :U   # Undoes all changes on the current line

 

5. Importing files into vi:

 

Code Block
languagebash
vi vi_file
ESC
:r import_file

 

6. Searching and replacing in vi:

6a.find a string of text in vi:

vi vi_file

Esc
Code Block
languagebash
 /text   # look for "text"
Enter

get the first result, and press N to find the next one.

6b. search and replace in vi:

vi vi_filename

Esc
Code Block
languagebash
 :%s/text/newtext   # replace "text" with "newtext"