Impossible tri-bar

Digital Phenomena - Your first stop for internet consultancy 
Advanced vi

Page 2 — File Manipulation

So far, you've moved around within one single vi file. Let's step back a minute and review how you can manipulate that vi file within a Unix system.

Typing vi filename opens the file - but you knew that already. Any other file manipulation - saving, recovering, or quitting a file - must be done in edit mode. If you're not sure whether you're in edit mode, hit the Escape key before doing anything.

If you want to save your work, all you have to do is type:

    :w!
This tells the system to write the newest version of the file into the directory where the file lives. If you've made a bunch of unsaved changes, then decided you'd rather revert back to the file you started with, go to edit mode and type:
    :e!
This will tell the editor to return to the last written (saved) version of the file. If you'd rather bail on the file, just switch to edit mode and type:
    :q!
And you'll have quit vi.

One of the neatest things about vi is that you can string a few commands together. So if I was in a file and wanted to save my changes and quit, I could just type:

    :wq!

You also can perform the following handy vi tricks (remember, these must be done in edit mode, so hit the Escape key if you can't remember which mode you're in):

To save the file you're working in as a different filename, type:

    :w%.newfilename
where newfilename is, obviously, the new name of the file.

To save just part of the file as a new file (which is a handy thing to know if you're breaking down a Web page into a series of server-side includes), figure out the line numbers of the first and last lines in the chunk o' file you want to save (pressing control-g displays all the line numbers in the document), then type:

    :l1,l2w newfile
where l1 is the first line of the chunk, l2 is the last line of the chunk, and newfile is the name of the new file.

To recover your file after you've blown your buffer or the system has crashed on you, you'll need to reopen the file and tell the editor to go searching for the last edited copy. To do this, type:

    vi -rfilename
You will need to do this at least once in your life.

To open a file at a particular pattern (which comes in handy if you're debugging your HTML and you know what you need to fix, or if you've got an HTML file with a 50-line script within the <head> tags and you want to skip ahead to the body), type:

    vi +/pattern filename
So if I wanted to open the file monkeys.html at bananabanana, I'd type:
    webmonkey:/usr/diva/> vi +/bananabanana monkeys.html

next page»


|Home|About Us|Services|Search|
|Software|Products|Support|Links|Latest|
W3C validatedW3C validated CSSCompatible with all browsers