Vi For Smarties
Lesson Eight
Reading From and Writing To Other Files
- 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.
- 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.
- 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.
- Use :1,10 w >> outfile to append
lines 1 through 10 inclusive from the current file to
outfile nondestructively.
Advanced Search and Replace
- Use :s/foo/bar/ to replace the first
occurrence of the word foo on the current
line with the word bar.
- Use :s/foo/bar/g to replace all
occurrences of the word foo on the current
line with the word bar.
- 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.
- 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.
- 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
- 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.
- 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.
- 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.
- 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.