Untitled Document

Chapter - 7 Vi Editor

No Matter what commands we have run and execute , we need to create files or edit some files in Unix / Linux to create a C or shell programs .Linux/UNIX provide us a very strong editor called vi which is developed by Bill Joy for BSD system , the program is now used as standard editor in all UNIX and LINUX platforms.Bram Moolenar improved it and called it as Vim ( vi Improved). In This chapter we will discuss about the vi editor and few features of vim editor.

Like other editors vi has some built in commands which can copy and move text, delete ,find ,replace . vi offers cryptic and sometimes mnemonic internal commands for editing work . It makes complete use of keyboard where practically every key has a function.

vi Basics - 

To understand the vi editor , lets create a file sample.txt and add some text to that file . Invoke command -

vi sample.txt

The vi displays you a full screen with the full name shown at the bottom with the qualifier [New file].The cursor position will be at the top and all remaining lines of screen displays ~.The symbol represents that the line is blank and you can't move your cursor there as the lines are non existent lines.

The last line is reserved for commands that you can enter to act on text .This line is also used to display messages by system

We are now in command mode on of the three modes of vi .This is the mode where you can pass commands ( we will see the commands in our upcoming discussions) to run on text .Pressing a key doesn't show anything on screen but it may perform actions like moving the cursor , deleting text or line .

You can't use the Command Mode to enter or replace text

To insert a text , you need to switch to Input Mode . Press i and you are in this mode ready to insert text .Start inserting some text and few lines .After text entry is complete the cursor is positioned the last character of the line this line is called current line and the character where the cursor is stationed is the current cursor position

Now press [Esc] key to revert to command mode . Press it again and you hear a beep; a beep in vi indicates that a key has been pressed unneccessarily.

The file sample.txt doesn't exist yet .Actually, The text that you have entered hasn't been saved on disk but it exist in some temporary storage called buffer . To save the entered text you need to switch to ex Mode ( also known as last line mode). to invoke this mode press a : (colon) and press X and hit enter .

: x [enter]

Now the file sample.txt is saved on disk and vi returns the shell prompt.Before we move ahead , lets summarized the modes that we use in vi :

  • Command Mode - The default mode of the editor , where every key pressed is interpretted as a command to run on text . you will have to be in this mode to copy or delete text (via command) .unnecessary pressing of [Esc] key in this mode will sounds a beep .
  • Input Mode - every key pressed in this mode will be actually dispalyed on screen as a text . this mode is onvoke by pressing i key
  • ex Mode - The mode used to save the files and perform substitution .Pressing a : in the command mode invoke this mode . You can enter ex mode command followed by enter .

The file .exrc -

The default behaviour of vi is adeequate for novices , but you will feel the need to customize it to behave in a way that makes program writing easier. vi reads the file .exrc which is present under your home directory $HOME/.exrc (same as ~/.exrc in some shells) on startup.If ls -a doesn't show this file in your home directory , you can create or copy one .Linux users must note that vim generally doen't use .exrc but .vimrc.

Many ex Mode can be placed in this file so they are available in every session. you can create abbrevations, redefine your keys and also change variable settings . Your .exrc will contain all the shortcuts and settings taht you use regularly.

Few Key Strokes and Tips

Here are few points that you must keep in mind when you are doing work with vi -

  • Undo - If you have made a mistake in editing either by wrongly editing the statement or by wrongly deleting a word/line . Then first measure is press [Esc] and press u.Linux users user should use [ctrl-r]
  • Clearing the Screen - If the screen gets garbled for some reason , use [ctrl-l] in the command mode to redraw the screen . If you hit [ctrl-l] in input mode you will see the symbol ^L on the screen , backspace it , press [Esc] and hit [ctrl-l].
  • Avoid PC Navigation Keys - As far as possible avoid the PC navigation keys , like Up, Down ,Left,Right ,[pageup] ,[pagedown]. Vi has versy strong set ok keys for navigation purpose..
vi Commands are case sensetive ; a and A are different commands .Make sure to to turn off your caps lock

Input Mode - Entering and replace text 

In this section we will see the command that we will take you to insert mode from command mode. Here are the modes that will take us to insert mode -

  • Insert and append ( i, a , I and A)
  • Replace ( r , R, s and S)
  • Open a line ( o and O )

Always keep in mind that after you have completed the text entry using any of these commands ( except r) , you must return to command mode.

Insertion of text ( i and a ) -

The simplest way to insert the text in vi is Press i (existing text will be shifted right ) and you will be in this mode , at the bottom of your vi you will see a line INSERT MODE to the right corner of screen. If the i command is invoked with the cursor positioned on existing text , text on its right will be shifted further without being overwritten .

There are other method to insrt text . We can append the text to the right of the cursor position by pressing a . The text will be inserted to the right of cursor position.

Press [Esc] once you are done with insertion

Insertion of Text at Line Extremes ( I and A ) -

I and A behaves some what like i and a except that they insert text at line extremes.

  • I - Inserts text at begining of line
  • A - Appends text at end of line
some times you want to print some text like /###########/. looks like 10 # are here . Insert / in insert mode and then press[Esc] and enter 10a# . This is helpful when you need to enter comments in C or shell programming

Opening a New line (o and O) -

Many a times we need to write a text in new line , people follow the conventional method , to go to the end of line and then press [ enter] to open new line . In vi we can directly insert a line by pressing o and O from cureent line .

  • o - will open line below the cureent cursor position
  • O - will open new line above the current line or cursor position.

Replacing Text ( r, s, R and S ) -

To replace existing text vi produces mainly four commnads , Actually we have many more commands we will see in the upcoming text and chapters .For current context we will see these four commands shown on header. To replace a single character with another , you can use - r followed by the character that you want to replaces the one under the cursor. you can replace single character in vi only by this way .vi automatically swithced to insert mode when r is pressed and switches to command mode as soon as the new character is entered. No need to press [Esc] when using r as vi is expecting only one character anyway.

when you want to replace one character with multiple character press s and vi deletes the character under cursor and switches to input mode Now enter your text e.g hello and press [Esc]. To replace multiple character use a repeat factor . 2s replaces 2 charcter with new text.

Similarly R- replaces all text on right side of the cursor position. S- Replaces the entire line iirespective of cursor position ( Existing line disappears)

Here is the summary for input mode commands-

Command Function
i Inserts text to the left of cursor ( existing text shifted to right)
a Appends text to the left of cursor ( existing text shifted to right)
I Insert text at begining of line ( existing text shifted to right)
A Append text at the end of line
o Insert line below current line ( cursor postion)
O insert line Above current line (cursor position)
r Replaces single character under cursor with any number of character
s Replaces single character under cursor with any number of character
S Replaces entire line

Saving Text and Quiting - The ex Mode -

We have now created the file and inserted the text into it , when we edit the file , the copy of the file gets edited original file isn't disturbe as such , but only its copy is stored in buffer which is temporary form of storage .To store the contents of buffer into your disk file , you need to periodically save it . When we talk of saving file , we actually mean saving this buffer.

Saving Your work ( :w) -

we have already seen one command :x in our previous discussion to save and quit the vi editor . But if we want to continue writing and saving the text in vi without quiting it then we have a command :w which will save your contents from buffer to existing file without quitingvi .

Make sure that you should execute this command regularly to save your text in file.You can even save the data to a seprate file by specifying filename to :w

It's common practice to ignore the readonly message while opening the file in vi whose write mode bit is not set. when you attempt to save this file it gives you warning that file is read only , not worry , we can save the file with different name using :w<file_name> make sure that file name given doen't exist.

Saving and quiting ( :x and :wq) -

:w will save your file in vi and will allow you to remain in vi editor . To save and quit vi editor you can run :x or :wq followed by file name

The best way to save and quit vi editor is to use ZZ , a command mode command instead of using :x or :wq

Abort Editing (:q) -

Some times we need to abort / quit editing without saving the buffer . Press :q . vi also has a safety mechanism that prevent you from aborting accidently if you have modified the fiile in any way. The following typical message you will see .

No write since last change (:quit ! overrides)

If buffer has changed and you still want to abandon the changes then use :q!

Writing Selected Lines -

we can even write the selected lines to another file using :w command ( ex mode command) e.g

:10,50w fact.ksh

saves line 10 to 50 from current file to the file fact.ksh . You can even save single line .

:5w fact.ksh

writes fifth line of current file to fact.ksh

There are two symbols that have special meaning .(dot ) represent current line of the file and $ represent last line of the file . We can use this with :w commands

: .w fact.ksh ---------------Saves current line ( where cursor is positioned)
: $w fact.ksh ---------------Saves last line
: . , fact.ksh ----------------Saves current line through end

If fact.ksh file exists and is writable , vi issues warning "fact.ksh" file exists - use "w! fact.ksh" to overwrite . The vi clearly tells you to use ! to overwrite the file using ! . As discussed ! is the universal overriding operator and we will use it often .

Save and exit commands of the ex Mode -

Command Function
:w Saves file and remians in editing mode
:x Saves file and quit vi editing mode
:wq Saves file and quit vi editing mode
:w test1.ksh Like Save as .... In microsoft
:w! test1.ksh Same as above but overwrites the existing sfile
:q Quits editing mode when no changes are made to file
:q! Quits editing mode but after abonding the changes
:10,50w fact.ksh writes the line 10 to 50 to file fact.ksh
:.w fact.ksh writes current line to fact.ksh
:$w fact.ksh writes last line to fact.ksh

Navigation-

we have seen the different modes and commands of those modes . We also need to navigate through files , to move the cursor , vi provides 4 different keys to move your cursor up, down, right, left .

To Move cursor up use -

  • k - Moves cursor up
  • j - Moves cursor down

To Move cursor along a line use -

  • h - Moves cursor left
  • l - Moves cursor right

we can use repeat factor command to move the cursor - 4k will move the cursor 4 lines up , thus 20h will move cursor 20 characters to the left .

Word Navigation ( b , e and w) -

Moving with the charater using cursor keys is not sufficient , sometimes we need to navigate through words in forward and backward directions. Vi has provided the three basics commands which does this task .

  • b - Moves back to begining of word
  • e - Moves forward to the end of word
  • w - Moves forward to begining of word

Here also you can use the repeat factor 3b will move you 3 words back along the line .Try the commands B,E and W and see what results you get .

Moving To Line Extremes ( 0 ,| and $ ) -

Some times we need to move to the line extremes . This activity we can do that by using 0 , | and $.To move to the first character of a line , use

0 (zero) or |

The | takes a repeat factor and we can move cursor to any column , to move to column 20 use 20| . To move to end of the current line use $

$ - Move to end of line

Scrolling -

we can even move to file by scrolling a page . Following are the commands that will help us to scroll the page forward and backward.

  • [ctrl-f] - Scrolls Forward
  • [ctrl-b] - Scrolls Backward
  • [ctrl-d] - Scrolls half page forward
  • [ctrl-u] - Scrolls half page backward

we can even use the repeat factor 10[ctrl-f] will scroll 10 pages forward .

Absolute Movement (G) -

when you open a file in vi , it shows you the total number of lines in the last line .To know your current line number you can press [ctrl-g] . To move to different line numbers we can run following commands

  • 10G - Goes To line number 10
  • 1G - Goes To line number 1
  • G - Goes to end of file
You can perform above operations using ex mode command , :10 :1 and :$ will take you to line number 10 , 1st line and last line respectively

Deleting Text ( x and dd ) -

We can delete the text under the cursor using x command . The command will delete the single character under cursor . The character under cursor gets deleted and text on right gets shifted to left .You will be surprised to see that , when the cursor is at the end of line , x will start deleting the character from left. This is usually done by X .Keep x pressed and you will see that text will be deleted to the begining of line.

we can even delete the entire line by dd , move the cursor on the line which is to be deleted and press dd entire line will be deleted . You use the repat factor like 6dd will delete six lines from current cursor position

Copying Text ( y and p ) -

vi uses term yanking for copying text and hence it use command y for copying it . To copy ( or yank) one or more lines use following commands -

  • yy - Yanks Current Line
  • 10yy - Yanks current line and below 9 lines

Now to copy this yanked text you need to use put command - p and P . The text can be copied to below or above the line we cannot copy it to the left or right of the line . But if you want to place an entire line at the end of another line then you have to place it below the line first and then join the two lines . we will discuss in next topic .

Joining Lines ( J) -

Like normal word processor we cannot joins the lines by deleting the the last characters and text of current line in vi . To join the current line and line following it we need to use J (Capital) . J removes the newline character between two lines to pull up the below line .

4J - Joins the current line with below 3 lines

Undo Instruction ( u and U ) -

While editing the file or text we often commit some mistake and need to restore the file to original . To reverse the changes before we do anything press u . It will undo you changes made to the file .

- Must use in command mode , press [esc] if neededs

If we have made too many changes to a single line and want to discard all the changes made to the line we can use U . But make sure that your cursor in on the line which you want to undo .All modifications that have been made since the cursor was moved to this line .

- Don't move way from current line
Multiple undo u may even restore your file to original .You can redo you work by pressing [ctrl-r].Repeat factor can be used in undo and redo 10u will undo last 10 changes same 10[ctl-r] will redo last 10 changes

Searching A Pattern -

Sometimes we need to find the particular word or a pattern in a file . vi provides us a very strong searching commands which can search word/string in forward or backward direction . Let's see by an example how vi searches the pattern in a file .e.g you want to search string mangesh in a file , then run following command .

/mangesh [enter] - / tells vi to search the string in forward direction

vi searches the string in a forward direction from the current position and search till the end of file , if pattern didn't find in forward direction vi will go top and try to search it .If the search still fails vi will display message - Pattern not found . Like the forward search we have one more option which will do backward search and will perform similar search operation .

?mangesh [enter] - ? tells vi to search the string in backward direction

Repeating Last search Pattern ( n and N ) -

To find the occurences of the searched pattern in a file , we can use n command to move forward direction. Basically n does the repeates search in same direction of original search . N performs the reverse part of it , it reverses the direction used by n .

n Dosen't necessarily repeat a search in forward direction; direction depend on the search command used . If you used ?mangesh and press n then also follows the same direction . In that case N will repeat the search in Forward direction.
Note - You can start up vi by specifying a pattern .use +/ symbol before the pattern
vi +/mangesh fact.ksh
The cursor will be located at the first instance of the pattern . you can then use n and N in the usual way for locating the next instance of the string . If pattern contains multiple words , enclose them in double quotes .
Command Function
/string Searches the string pattern in forward direction
?string Searches the string pattern inbackward direction
n Repeats the search pattern in the direction along which previous search was made
N Repeats the search pattern in the direction opposite to that along which previous search was made

Substitution - Find and Replace ( :s ) - 

Vi offers you find and replace option , which uses the following syntax -

:address / source_pattern / targetpattern / flags

The source patten is replace by the target pattern on the specified address in command .g is the most commonly used flag which substitutes all the occurences of the pattern in a file.The following example show the typical find and replace command -

:1,$s /mangesh/nikhil/g

If we remove g flag , then substitution will work only for the first occurence of the patern in a file .

The command will replace mangesh with nikhil for all the occurences in file.Instaed of 1,$s we can use % sign , which is most commonly used in substitution command. Here are some more examples of substitutions -

    :1,20s /mangesh/pande/g -----------------------------Mangesh will be replaced by pande from line 1 to 20
    :.s /test/example ----------------------------------------- test will be replaced by example for current line
    :$s /test/example ---------------------------------------- test will be replaced by example for last line
    :1,$s/mangesh/Ashish/gc ------------------------------ option c(confirmation) flag will make it interactive    

The fetaures that we have coverd so far are good enough for a beginner to start with vi editor . we will explore some more advanced commands and their usage in our upcoming Vi editor chapter.

Untitled Document Scroll To Top Untitled Document