dcsimg

Absolutely Essential Vim/vi Commands Page 2

By Joe Brockmeier (Send Email)
Posted Nov 1, 2010


More on Vim

Search and Replace

To search through the document, use the / key to initiate a forward search, or ? to initiate a backward search.

To search and replace, use :s with the range of lines and search terms. Like so:

:%s/old/new/

The % means "global," but you can replace that with a range of lines, like this:

:1,15s/old/new/

And I prefer to use the c (confirm) and g (global) options too, so when searching it will search the entire line and not just the first occurrence of a string.

A usual search would look something like :%s/old/new/gc, and when you hit Enter you'll be prompted before you make changes. I recommend using confirm; otherwise you can wind up with unexpected results.

Undo

What if you've made an edit you didn't want to make? Easy, use the undo (u) command. If you didn't mean to undo what you did -- and it's easy to accidentally hit u -- use Ctrl-r to redo the last change.

Quick note: If Vim is in vi-compatibility mode, it will have only one "level" of undo. In normal Vim mode, you can undo many, many changes. But vi undoes only the most recent change.

Saving, Quitting and More ...

One of the things that's severely non-obvious while working with Vim the first time is how do I get the heck out of here? You can quit Vim in a number of ways, but I'll show the most usual ones.

First, if you want to save your changes before exiting Vim, use :w or save and exit in one action with :wq.

Don't want to save your changes? It happens. No problem, just use :q! if you realize that you've made some edits that you don't want to save, and they are too complex to easily undo before exiting.

Note that you can also write changes to a different filename by using :w newfile.

So much more ...

This is just a short and sweet intro to Vim for emergencies or minimal usage. You could do much, much more with Vim if you wanted. Be sure to read through the Vim tutorial by running vimtutor, and look through Vim's documentation by running :help. But in a pinch, this list of commands should get you through.

GNU Screen is a powerful ally, use it well and often, you'll find it can help make life much easier.

Joe 'Zonker' Brockmeier is a freelance writer and editor with more than 10 years covering IT. Formerly the openSUSE Community Manager for Novell, Brockmeier has written for Linux Magazine, Sys Admin, Linux Pro Magazine, IBM developerWorks, Linux.com, CIO.com, Linux Weekly News, ZDNet, and many other publications. You can reach Zonker at jzb@zonker.net and follow him on Twitter.

Follow ServerWatch on Twitter

Page 2 of 2


Comment and Contribute

Your name/nickname

Your email

(Maximum characters: 1200). You have characters left.