One of the reasons I prefer to do my fast fixes in vi is because it's
far quicker than downloading a file, fixing it in an app, and then uploading it again. One of the most frequent fixes I do is searching for and replacing a string of characters in a file.
Searching for text is easy: To search for a string of characters in a document, type:
The editor will look for that string from the cursor forward, through the rest of the document. You can also search backwards, by typing:
So if I had a document that read like this:
It may not be the only Unix text editor out there, but it's the only one I'm writing about today. This editor is notable for the uniquely named clones it's spawned: elvis, stevie, vile, and vim.
and my cursor was right before the "u" in "uniquely," I would type ":/it's" if I wanted to go looking for the next instance of "it's" in the document. On the other hand, if I'm looking for the word "Unix," I'd type:
Note that this search command only works on a one-shot basis: If you're looking for multiple instances of the word "elvis," you'd repeat your search string by typing ":n" or ":."
(any time you type a period, it tells the editor to repeat the last command).
We've tackled searching, so let's move on to replacing. There are a lot of ways to do this, none of them particularly graceful. To replace a character in a word - say you wanted to change "vile" to "vibe" - make sure the cursor highlights the character l, and type rb (the second letter becomes the replacement letter). Fairly simple, yes? In fact, this is just a rehash of the last vi article.
If you're set to tank a line of text and write over it, just move your cursor to the beginning of the line, type cc, and begin typing your new text.
Now it's time for vi's über-trick: searching and replacing. The command is frightening enough to merit its own line:
where "string" is the word you're searching for and "string2" is the replacement word. The whole command looks a little gory, but it works.