View RSS Feed

DarkLordofthePenguins

Vim hack: doing edits over many files

Rate this Entry
by , 07-27-2010 at 03:49 PM (561 Views)
There are two ways to do edits over many files. One (the way to avoid atall costs) is to tediously edit each and every one by hand. The other way is to write a script, either in sed, awk, or the scripting language for whatever text editor you're using.

The script method works fine, as long as the edits you're doing can be expressed as program commands. But what if they aren't? What if they're keystrokes, like 1GP (to put text at the beginning of each file), or {j!}fmt (format a paragraph). Some of these can be implemented using scripts, but sometimes a quick-and-dirty method is more efficient.

Fortunately, Vim has a special buffer for storing a sequence of keystrokes. You can record keystrokes to the buffer for later use, then repeat the keystrokes from the buffer. To start recording keystrokes, type q and then the character for the buffer you want to record to. To stop recording, hit q again. Any keystrokes you type between these two will be recorded in the buffer with the given name. To repeat the keystrokes, type @ and then the name of the buffer.

qx - record keystrokes to the buffer marked x.
q - stop recording.
@x - repeat the sequence of keystrokes stored in x.

Now here's where the real time-saving part comes in. Make sure you type :w<enter>:n<enter> before you stop recording. Now when you repeat keystrokes, it will not only do the edits but also save and move on tothe next document. But this isn't good enough, because you still have to move between the @ key and the key for the buffer. Wouldn't it be nice if you could just hold down one key to do it?

That's where key mappings come in handy. Type the following in ex mode:

:map = @x

Replace x with the name of the buffer.

Now every time you press the = key, Vim will repeat everything in the buffer. Type :rew to go back to the first file, and hold down the = key (or whatever key you mapped) until you get to the last file. Vim will edit each file it comes across.

Let's review the steps:

1. Record the keystrokes, along with :w<enter>:n<enter>, using q.
2. :map = @x to map the keystrokes to a single key.
3. :rew to get to the first file.
4. Hold down the = key until you get to the last file.

Using this method, you can carry out a single edit to possibly hundredsof files in a matter of seconds.

Submit "Vim hack: doing edits over many files" to Digg Submit "Vim hack: doing edits over many files" to del.icio.us Submit "Vim hack: doing edits over many files" to StumbleUpon Submit "Vim hack: doing edits over many files" to Google

Tags: None Add / Edit Tags
Categories
Uncategorized

Comments

  1. Guest's Avatar
    There is something about Vim... I can't really get used to it. I always end up using Nano.