Vi For Smarties

Lesson Eight


Reading From and Writing To Other Files

  1. Use :r infile to read in the contents of infile starting at the line under the current one. Put a line number in front of the r to read in the contents of infile starting at the line under the one specified.
    Example: :25r foo.txt will read in the contents of the file named foo.txt starting at the line under line 25. Thus, the first line of foo.txt will become line 26 in the current file.
  2. Use :r !command to read in the output of command starting at the line under the current one. Put a line number in front of the r to read in the output of command starting at the line under the one specified.
    Example: :25r !date will read in the current date and time onto line 26.
  3. Use :w outfile to write the contents of the current file to a file named outfile. Put a line number range in front of the w to write only those lines to outfile.
    Example: :1,10 w outfile writes lines 1 through 10 inclusive from the current file into outfile.
  4. Use :1,10 w >> outfile to append lines 1 through 10 inclusive from the current file to outfile nondestructively.

Advanced Search and Replace

  1. Use :s/foo/bar/ to replace the first occurrence of the word foo on the current line with the word bar.
  2. Use :s/foo/bar/g to replace all occurrences of the word foo on the current line with the word bar.
  3. Use :%s/foo/bar/g to replace all occurrences of the word foo in the current file with the word bar. Leaving off the g at the end only replaces the first occurrence of foo on each line of the current file.
  4. Use :%s/foo//g to delete all occurrences of the word foo in the current file. Leaving off the percent sign (%), of course, only does this for the current line.
  5. Use :%s/foo/bar/gc to have Vi query you before each attempt to replace the word foo with the word bar.

Advanced Vi Invocation

  1. Use vi +/foo when invoking Vi from the command prompt to have it automatically move the cursor to the first occurrence of the string foo in the first file being edited.
  2. Use vi +24 myfile.txt when invoking Vi from the command prompt to have it start with the cursor on line 24 of myfile.txt. Replace the line number and filename with whatever is appropriate.
  3. Use view myfile.txt to start Vi in read-only mode on the file myfile.txt. On systems which do not support symbolic links, such as MS-DOS, try vi -R myfile.txt instead.
  4. NOTE: It is sometimes necessary to invoke clones of Vi by their appropriate program name, such as vim under MS-DOS.

Congratulations, you're done with Vi For Smarties! For a more advanced tutorial, see Walter Alan Zintz's The Vi/Ex Editor.


Copyright © 2001 jerry_y_wang@yahoo.com. All rights reserved.