How to Use the vi Editor* Copyright 1991 by Simon Fraser University. Reprintedwith permission.* The vi editor is available on almost all Unix systems.* vi can be used from any type of terminal because it doesnot depend on arrow keys and function keys--it uses thestandard alphabetic keys for commands.* vi (pronounced "vee-eye") is short for "vi"sual editor. Itdisplays a window into the file being edited that shows 24lines of text. vi is a text editor, not a "what you see is whatyou get" word processor. vi lets you add, change, anddelete text, but does not provide such formattingcapabilities as centering lines or indenting paragraphs.Starting viYou may use vi to open an already existing file by typing # vi <filename>where "filename" is the name of the existing file. If the fileis not in your current directory, you must use the fullpathname.Or you may create a new file by typing # vi <new file name>where "newname" is the name you wish to give the newfile.
To open a new file called "test," enter # vi testOn-screen, you will see blank lines, each with a tilde (~) atthe left, and a line at the bottom giving the name and statusof the new file:~ "test" [New file]vi Modesvi has two modes: command mode insert modeIn command mode, the letters of the keyboard performediting 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 andsentences. Unlike many word processors, vi starts up incommand mode.Entering TextIn order to begin entering text in this empty file, you mustchange from command mode to insert mode. To do this,type i
Nothing appears to change, but you are now in insert modeand can begin typing text. In general, vis commands do notdisplay on the screen and do not require the Return key tobe pressed.Type a few short lines and press <Return> at the end ofeach line. If you type a long line, you will notice the vidoes not word wrap, it merely breaks the lineunceremoniously 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 CursorTo move the cursor to another position, you must be incommand mode. If you have just finished typing text, youare still in insert mode. Go back to command mode bypressing <Esc>. If you are not sure which mode you are in,press <Esc> once or twice until you hear a beep. When youhear 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 spaceWhen you have gone as far as possible in one direction, thecursor stops moving and you hear a beep. For example, you
cannot use l to move right and wrap around to the next line,you must use j to move down a line. See the section entitled"Moving Around in a File" for ways to move more quicklythrough a file.Basic EditingEditing commands require that you be command mode.Many of the editing commands have a different functiondepending on whether they are typed as upper- orlowercase. Often, editing commands can be preceded by anumber to indicate a repetition of the command.Deleting CharactersTo delete a character from a file, move the cursor until it ison the incorrect letter, then type xThe character under the cursor disappears. To remove fourcharacters (the one under the cursor and the next three) type 4xTo delete the character before the cursor, type X (uppercase)Deleting WordsTo delete a word, move the cursor to the first letter of theword, and type dw
This command deletes the word and the space following it.To delete three words type 3dwDeleting LinesTo delete a whole line, type ddThe cursor does not have to be at the beginning of the line.Typing dd deletes the entire line containing the cursor andplaces the cursor at the start of the next line. To delete twolines, type 2ddTo delete from the cursor position to the end of the line,type D (uppercase)Replacing CharactersTo replace one character with another: 1. Move the cursor to the character to be replaced. 2. Type r 3. Type the replacement character.The new character will appear, and you will still be incommand mode.
Replacing WordsTo replace one word with another, move to the start of theincorrect word and type cwThe 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 theoriginal. Press <Esc> to get back to command mode. Toreplace three words, type 3cwReplacing LinesTo change text from the cursor position to the end of theline: 1. Type C (uppercase). 2. Type the replacement text. 3. Press <Esc>.Inserting TextTo 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 TextTo 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.Opening a Blank LineTo insert a blank line below the current line, type o (lowercase)To insert a blank line above the current line, type O (uppercase)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 3JUndoingTo undo your most recent edit, type uTo undo all the edits on a single line, type U (uppercase)Undoing all edits on a single line only works as long as thecursor stays on that line. Once you move the cursor off aline, you cannot use U to restore the line.Moving Around in a FileThere are shortcuts to move more quickly though a file. Allthese 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 ofscreen
L to last line ofscreen G to last line of file 1G to first line of file <Control>f scroll forward onescreen <Control>b scroll backward onescreen <Control>d scroll down one-halfscreen <Control>u scroll up one-halfscreenMoving by SearchingTo move quickly by searching for text, while in commandmode: 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 nTo repeat the search in a backward direction, type NClosing and Saving a File
With vi, you edit a copy of the file, rather than the originalfile. Changes are made to the original only when you saveyour edits.To save the file and quit vi, type ZZThe vi editor editor is built on an earler Unix text editorcalled ex. ex commands can be used within vi. excommands 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 closingfiles.To save the edits you have made, but leave vi running andyour file open: 1. Press <Esc>. 2. Type :w 3. Press <Return>.To quit vi, and discard any changes your have made sincelast saving: 1. Press <Esc>. 2. Type :q! 3. Press <Return>.Command SummarySTARTING vi
vi filename edit a file named"filename" vi newfile create a new filenamed "newfile"ENTERING TEXT i insert text left ofcursor a append text right ofcursorMOVING THE CURSOR h left one space j down one line k up one line l right one spaceBASIC EDITING x delete character nx delete n characters X delete character beforecursor dw delete word ndw delete n words dd delete line ndd delete n lines D delete characters fromcursor to end of line r replace character undercursor
cw replace a word ncw replace n words C change text from cursorto end of line o insert blank line belowcursor (ready for insertion) O insert blank line abovecursor (ready for insertion) J join succeeding line tocurrent cursor line nJ join n succeeding linesto current cursor line u undo last change U restore current lineMOVING AROUND IN A FILE 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 ofscreen L to last line ofscreen G to last line of file 1G to first line of file <Control>f scroll forward onescreen
<Control>b scroll backward onescreen <Control>d scroll down one-halfscreen <Control>u scroll up one-halfscreen n repeat last search insame direction N repeat last search inopposite directionCLOSING AND SAVING A FILE ZZ save file and thenquit :w save file :q! discard changes andquit fileBeside it there are various command which can beused to control the behavior of vi editor, some of themmost command are there to rememberEsc +:+w+q save andexit form fileEsc+:+q+! exitwithout saving
Esc+:+set nu to showhidden lineEsc+:+/test to findtest word in forward directionsEsc+:+21 to movecursor in line number 21Esc+:+2+yy to copy 2line form cursorEsc+:+p to pastethe copied line below the crusorEsc+:+dd to removethe entire lineEsc+:+4+dd to remove4 line below of cursorEsc+:+x to removesingle characterEsc+:+e to go toend of the wordEsc+:+h to go onecharacter backWe have written a complete article about Vi editor.You can read it for more information about vi editor.Beside it there are various command which can beused to control the behavior of vi editor, some of themmost command are there to remember
Esc +:+w+q save andexit form fileEsc+:+q+! exitwithout savingEsc+:+set nu to showhidden lineEsc+:+/test to findtest word in forward directionsEsc+:+21 to movecursor in line number 21Esc+:+2+yy to copy 2line form cursorEsc+:+p to pastethe copied line below the crusorEsc+:+dd to removethe entire lineEsc+:+4+dd to remove4 line below of cursorEsc+:+x to removesingle characterEsc+:+e to go toend of the wordEsc+:+h to go onecharacter backWe have written a complete article about Vi editor.You can read it for more information about vi editor. a-The add command. After it, you can input text that starts to the right of the cursor.
i-The insert command. After it, you can input text that starts to the left of the cursorArrow keys-Move the cursor up, down, left, or right in thefile one character at a time. To move left and right you canalso use Backspace and the space bar, respectively. If youprefer to keep your fingers on the keyboard, move thecursor with h (left), l (right), j (down), or k (up). w-Moves the cursor to the beginning of the next word. b-Moves the cursor to the beginning of the previous word. 0 (zero)-Moves the cursor to the beginning of the current line. $-Moves the cursor to the end of the current line. H-Moves the cursor to the upper-left corner of the screen (first line on the screen). M-Moves the cursor to the first character of the middle line on the screen. L-Moves the cursor to the lower-left corner of the screen (last line on the screen). The only other editing you need to know is how to delete text. Here are few vi commands for deleting text: x-Deletes the character under the cursor.
X-Deletes the character directly before the cursor. dw-Deletes from the current character to the end of the current word. d$-Deletes from the current character to the end of the current line. d0-Deletes from the previous character to the beginning of the current line. To wrap things up, use the following keystrokes for saving and quitting the file: ZZ-Save the current changes to the file and exit from vi. :w-Save the current file but continue editing. :wq-Same as ZZ. :q-Quit the current file. This works only if you don’t have any unsaved changes. :q!-Quit the current file and don’t save the changes you just made to the file. If youve really trashed the file by mistake, the :q! command is the best way to exit and abandon your changes.The file reverts to the most recently changed version. So, ifyou just did a :w, you are stuck with the changes up to thatpoint. If you just want to undo a few bad edits, press u toback out of changes.
You have learned a few vi editing commands. I describemore commands in the following sections. First, however,here are a few tips to smooth out your first trials with vi: Esc-Remember that Esc gets you back to command mode. (I’ve watched people press every key on the keyboard trying to get out of a file.) Esc followed by ZZ gets you out of command mode, saves the file, and exits. u-Press u to undo the previous change you made. Continue to press u to undo the change before that, and the one before that. Ctrl+R-If you decide you didn’t want to undo the previous command, use Ctrl+R for Redo. Essentially, this command undoes your undo. Caps Lock-Beware of hitting Caps Lock by mistake. Everything you type in vi has a different meaning when the letters are capitalized. You don’t get a warning that you are typing capitals- things just start acting weird. :! command-You can run a command while you are in vi using :! followed by a command name. For example, type :!date to see the current date and time, type :!pwd to see what your current directory is, type :!jobs to see if you have any jobs running in the background. INSERT-When you are in insert mode, the word INSERT appears at the bottom of the screen.
Ctrl+G-If you forget what you are editing, pressing these keys displays the name of the file that you are editing and the current line that you are on at the bottom of the screen. It also displays the total number of lines in the file, the percentage of how far you are through the file, and the column number the cursor is on. Moving Around the FileBesides the few movement commands described earlier,there are other ways of moving around a vi file. To trythese out, open a large file that you can’t do much damageto. (Try copying /var/log/ messages to /tmp and opening itin vi.) Here are some movement commands you can use: Ctrl+F-Page ahead, one page at a time. Ctrl+B-Page back, one page at a time. Ctrl+D-Page ahead one-half page at a time. Ctrl+U-Page back one-half page at a time. G-Goto the last line of the file. 1G-Go to the first line of the file. (Use any number to go to that line in the file.)Searching for TextTo search for the next occurrence of text in the file, useeither the slash (/) or the question mark (?) character.Follow the slash or question mark with a pattern (string oftext) to search forward or backward, respectively, for thatpattern. Within the search, you can also use metacharacters.Here are some examples:
/hello-Searches forward for the word hello. ?goodbye-Searches backward for the word goodbye. /The.*foot-Searches forward for a line that has the word The in it and also, after that at some point, the word foot. ?[pP]rint-Searches backward for either print or Print. Remember that case matters in Linux, so make use of brackets to search for words that could have different capitalization.The vi editor was originally based on the ex editor, whichdidn’t let you work in full-screen mode. However, it didenable you to run commands that let you find and changetext on one or more lines at a time. When you type a colonand the cursor goes to the bottom of the screen, you areessentially in ex mode. Here is an example of some of thoseex commands for searching for and changing text. (I chosethe words Local and Remote to search for, but you can useany appropriate words.) :g/Local-Searches for the word Local and prints every occurrence of that line from the file. (If there is more than a screenful, the output is piped to the more command.) :s/Local/Remote-Substitutes Remote for the word Local on the current line. :g/Local/s//Remote-Substitutes the first occurrence of the word Local on every line of the file with the word Remote.
:g/Local/s//Remote/g-Substitutes every occurrence of the word Local with the word Remote in the entire file. :g/Local/s//Remote/gp-Substitutes every occurrence of the word Local with the word Remote in the entire file, and then prints each line so that you can see the changes (piping it through more if output fills more than one page).Using Numbers with CommandsYou can precede most vi commands with numbers to havethe command repeated that number of times. This is ahandy way to deal with several lines, words, or charactersat a time. Here are some examples: 3dw-Deletes the next three words. 5cl-Changes the next five letters (that is, removes the letters and enters input mode). 12j-Moves down 12 lines.Putting a number in front of most commands just repeatsthose commands. At this point, you should be fairlyproficient at using the vi command. Once you get used tousing vi, you will probably find other text editors lessefficient to use. Search ComputerNetworkingNotes.com