How to use Vi/Vim, The Full Tutorial

terminal.png

From wikipedia: vi is a screen-oriented text editor written by Bill Joy in 1976 for an early BSD release. The name vi is derived from the shortest unambiguous abbreviation for the command visual in ex; the command in question switches the line editor ex to visual mode. Current releases of vi are free and open source software, usually released under permissive free software licenses> such as the BSD License. vi is the commandline text editor of choice (well, not if you ask the emacs crowd), but the reason for it’s widespread use is that it can fit on a floppy disk to aid system recovery. It is a power editor with many options to navigate and manipulate text and we’ll covers the basics here.

Starting vi:

You may use vi to open an already existing file by typing
vi filename
where “filename” is the name of the existing file. If the file is not in your current directory, you must locate it and type the full path to that file.

Or you may create a new file by typing
vi newfilename

where “newfilename” is the name you wish to give the new file.

To open a new file called “newfilename” enter
vi newfilename

On the screen, you will see blank lines, each with a tilde (~) at the left, and a line at the bottom giving the name and status of the new file:

~

      "newfilename" [New file]

vi Modes

vi has two modes:

  • command mode
  • insert mode

In command mode, the letters of the keyboard perform editing functions (like moving the cursor, deleting text, etc.). To enter command mode, press the escape <Esc> key.

In insert mode, the letters you type form words and sentences. Unlike many word processors, vi starts up in command mode. To enter or edit text you must be in insert-mode, and by pressing the <i> key, vi will enter into that mode.

After typing ‘i’ it may look like nothing changes, but you are in inset mode. In general, vi’s commands do not display on the screen and do not require the Return key to be pressed. Type a few short lines and press <Enter> at the end of each line. If you type a long line, you’ll notice the vi application does not use a word wrap function, it simply breaks the line at the edge of the screen. If you make a mistake, pressing <Backspace> or <Delete> may remove the error, depending on your terminal type.

Moving the Cursor

To move the cursor to another position, you have to be in the command mode. Let’s say you are finished typing text but you are still in insert mode. Go back to command mode by pressing <Esc>. If you are not sure which mode you are in, press <Esc> once or twice until you hear a beep. When you hear the beep, you are in command mode.

The cursor is controlled with four keys: h, j, k, l.

     Key        Cursor Movement
     ---        ---------------
     h        left one space
     j        down one line
     k        up one line
     l        right one space

When you have gone as far as possible in one direction, the cursor stops moving and you hear a beep. For example, you can’t use l to move right and wrap around to the next line, you must use j to move down a line. We’ll cover how to move more quickly in just a moment.

Basic Editing

To edit commands you must be in command mode. Many of the editing commands have a different function depending on whether they are typed as upper or lowercase. Often, editing commands can be preceded by a number to indicate a repetition of the command.

Deleting Characters

To delete a character from a file, move the cursor until it is on the incorrect letter, then type

      x

The character under the cursor disappears. To remove five characters (the one under the cursor and the next four) type

     5x

To delete the character before the cursor, press

      X (uppercase)

Deleting Words

To delete a word you need to place the cursor to the first letter of the word, and type

      dw

This command deletes the word and the space following it.

To delete four words type

       4dw

Deleting Lines

To delete a whole line on text you need to type

       dd

The cursor does not have to be at the beginning of the line. Typing dd deletes the entire line containing the cursor and places the cursor at the start of the next line. To delete three lines, type

       3dd

To delete from the cursor position to the end of the line, type

       D (uppercase)

Replacing Characters

To replace one character with another character:

  1. Move the cursor to the character to be replaced.
  2. Type r
  3. Type the character you want to replace it with.

The new character will appear, and you will still be in command mode.

Replacing Words

To replace one word with another word, move to the start of the incorrect word and type

     cw

The last letter of the word to be replaced will turn into a $. You are now in insert mode and may type the replacement. The new text does not need to be the same length as the original. Press <Esc> to get back to command mode. To replace four words, type

     4cw

Replacing Lines

To change text from the cursor position to the end of the line:

  1. Type C (uppercase).
  2. Type the replacement text.
  3. Press <Esc>.

Inserting Text

To insert text in a line:

  1. Position the cursor where the new text should go.
  2. Type i
  3. Enter the new text.

The text is inserted BEFORE the cursor.

4. Press <Esc> to get back to command mode.

Appending Text

To add text to the end of a line:

  1. Position the cursor on the last letter of the line.
  2. Type a
  3. Enter the new text.

This adds text AFTER the cursor.

4. Press <Esc> to get back to command mode.

Joining LinesTo join two lines together:

  1. Put the cursor on the first line to be joined.
  2. Type J

To join three lines together:

  1. Put the cursor on the first line to be joined.
  2. Type 3J

UndoingTo undo your most recent edit, type

     u

To undo all the edits on a single line, type

     U (uppercase)

Undoing all edits on a single line only works as long as the cursor stays on that line. Once you move the cursor off a line, you cannot use U to restore the line.

Moving Around in a File

There are shortcuts to move more quickly though a file. All these work in command mode.

     Key            Movement

     ---            --------
     w            forward word by word

     b            backward word by word

     $            to end of line

     0 (zero)     to beginning of line

     H            to top line of screen

     M            to middle line of screen

     L            to last line of screen

     G            to last line of file

     1G           to first line of file

     <Control>f   scroll forward one screen

     <Control>b   scroll backward one screen

     <Control>d   scroll down one-half screen

     <Control>u   scroll up one-half screen

Moving by SearchingTo move quickly by searching for text, while in command mode:

  1. Type / (slash).
  2. Enter the text to search for.
  3. Press <Return>.

The cursor moves to the first occurrence of that text.

To repeat the search in a forward direction, type

     n

To repeat the search in a backward direction, type

     N

Closing and Saving a FileWith vi, you edit a copy of the file, rather than the original file. Changes are made to the original only when you save your edits.

To save the file and quit vi, type

     ZZ

The vi editor editor is built on an earler Unix text editor called ex. ex commands can be used within vi. ex commands begin with a : (colon) and end with a <Return>. The command is displayed on the status line as you type. Some ex commands are useful when saving and closing files.

To save the edits you have made, but leave vi running and your file open:

  1. Press <Esc>.
  2. Type :w
  3. Press <Return>.

To quit vi, and discard any changes your have made since last saving:

  1. Press <Esc>.
  2. Type :q!
  3. Press <Return>.

Copy between files in vi/vim

VI editor is a very powerful editor. Suppose you want to copy line numbers 1-10 and 23-77 of file A and paste them on file B at the same time, what will you do ?? Here I am giving a tip to do this :

Place the cursor on line no. 1
Press ESCAPE
Press Shift “(Shift double quotes)
Press a
Press 10yy [the number of lines you want to copy]

Now place the cursor on line no. 23
Press ESCAPE
Press Shift “(Shift double quotes)
Press b
Press 55yy [the number of lines you want to copy]

Now the first 10 lines have been copied in buffer “a” and next 55 lines have been copied in buffer “b”.

Now press ” : ” (COLON) to get the vi prompt. Hit e “Destination file name”

Once you enter the Destination file go to the line where you want the first 10 lines in buffer “a” to be inserted.

Press ESCAPE.
Press Shift “(Shift double quotes)
Press a.
Press p.

The first 10 lines in buffer “a” gets inserted.

Now go to the line where you want the rest 55 lines in buffer “b” to be inserted.

Press ESCAPE.
Press Shift “(Shift double quotes)
Press b.
Press p.

The rest 55 lines in buffer “b” gets inserted.

Search and Replace in Vi/Vim

In Vi or Vim, use the forward slash </> to search. Then type in your search string and hit <Enter>. You can navigate through occurrences of your search string using <n> to move forward and <N> to move backwards.

If you do not want Vim to highlight searches, set the following in your ~/.vimrc

set nohlsearch

To wrap searches around the file when using <n> and <N>, set the following in your ~/.vimrc

set wrapscan

Search and Replace

To begin a search and replace in Vi or Vim, start by hitting the colon <:>. This will allow you to enter a Vi command. Then, enter a search and replace command like so:

%s/old/new/g

This will search every line for ‘old’ and replace all occurrences in the line with ‘new’. You start by mentioning which lines to affect. In my example, I use ‘%s’. This translates to all lines. Then, I trail the command with ‘g’ (for global) to affect all occurrences in the lines defined by ‘%s’. Note that global does not mean the entire file!

Limiting the Replace

You can declare the search and replace for only the current line by removing the percent sign:

s/old/new/g

It is also possible to limit the affected line numbers. The next example only affects lines 40 through 42:

40,42 s/old/new/g

Eliminating the ‘g’ from the end will only replace the first occurrence per line defined in the search.

Regular Expressions

The search string can be the form of a regular expression. In the next example, I replace all numbers with the word ‘number’.

%s/[0-9]/number/g

Escaping Characters

You will have to escape out the slash </> if it is part of your search string:

%s/http:\/\//https:\/\//g

Use Any Delimiter

Alternatively, change your delimiter. It can be anything!

%s!http://!https://!g

Get Confirmation Before Changing

You can get confirmation for each replace by adding a ‘c’ to the end of your command.

How to go a particular line or word in vi

You can go to a particular line or word in a file using vi in several ways:

  • To make vi start at a particular line in a file, add +line_num to the command you use to start vi. Replace line_num with the line number, for example: vi +36 foo.c
  • If you’re already in vi, you can use the goto command. To do this, press Esc, type the line number, and then press Shift-g . If you press Esc and then Shift-g without specifying a line number, it will take you to the last line in the file.
  • You can also use the ex command line to go to a line. For instance, if you wanted to go to line 14, you could press Esc and then enter: :14
  • To search forward for some text, use the / (forward slash) command. Press Esc and then enter /pattern , replacing pattern with the text for which you want to search forward. For example, to find every instance of the word “blimp”, enter: /blimp To look for the next occurrence after the first, either press n or press / again and then press Enter. To go back to a previous occurrence, press Shift-n . To search backwards in a file, use the ? command.
  • To see what line you’re on at any time, press Ctrl-Shift-g . To number all lines, press Esc and enter: :set number

Suspend a VI session for shell

Ever want to run some shell commands while doing a vi edit session? Like, “what’s the name of that file” I want to use in this script I’m making?

Instead of exiting vi; doing the ls filenamepart*, and going back into vi, you can from a vi session:

enter “:”, then enter “shell”.

This suspends the vi session and gives you a command prompt where you can use any shell command. When finished, enter the “exit” command and you will be returned to the vi session.

VI and no disk space

If you get the error while opening a file in vi:

“There is not enough space in the file system.
[Press return to continue]”

and you know that you have space in your home directory, than simply use this command
in vi, say

:set dir=

then press:

:e .

You will be able to see the entire file.

Vi and Vim Cheatsheets

No Posts Found

Comments are closed.