Vim hack: applying an edit uniformly to a series of similar HTML files

Vim is a really great text editor, not just because it provides a lot of editing options, but also because it lends itself to a lot of creative tricks and hacks. This is one such hack. I discovered it a few years ago while exploring Vim’s keystrokes.  It allows you to apply an edit uniformly to several similar files. It works especially for HTML files. Sure, you can use CSS to quickly change the style of a series of HTML pages, but what if you want to change the content? This trick will allow you to do that.

Step 1: Open your files. Remember to only open the files you wish to apply the edit to, otherwise you will get undesired edits, or Vim will choke on one of the non-similar files.

Step 2: Type q followed by a character of your choice (say w). This will be your keystroke buffer.

Step 3: Go to the point in the first file where the editing will start. Here it’s crucial to use the / or ? keystroke for a regular expression search, rather than going to that point manually.

Step 4: Apply your edit. It can be anything you like, as long as you stay on the current file (for now).

Step 5: Go to command mode (if you’re not already there) and enter :w to save changes.

Step 6: Enter :n to go to the next file.

Step 7: Your buffer is now complete. Press q to leave recording mode.

Step 8: Type :map <char1> @<char2>, where the first character is the macro and the second character is the marker for your buffer (example: :map = @w).

Step 9: Hold down the = key (or whatever key you chose for your macro). The edit will be applied almost instantly to all your files.

This hack is especially useful if you have many web pages that you want to change on a content level. Even if you have hundreds of files, the edit will be applied to all of them in a matter of seconds.

NOTE: Is this hack not working for you? If so, please leave a comment on this blog post, and I will go back and fix whatever mistakes I made. Thanks.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s