Vim Macro Example

In this section, we’ll work through a simple example to get familiar with Vim Macros. We’ll edit a column in a tab separated file (TSV) using a macro.

TSV Example

Let’s say we have the following tab separated text1. Notice the last column, where all the cities are in capital letters:

04/15/2023      14.05   Coffee  MANCHESTER
04/17/2023      9.65    Food    MANCHESTER
04/27/2023      124.96  Hosting SAN JOSE

We’ll create a macro to change the case for the last column, which is city.

  1. First, start recording a macro by pressing q then a to store our macro in a:
    press q to start recording a macro
  2. Next, press W 3 times, or type 3W to move the cursor to the start of the last column.
  3. Then, press v to enter visual mode. Then type $ to select to the end of the line.
  4. Next, press ~ (tilda) to change case.
  5. Press 0 to return to the start of the row.
  6. Then, press j to move to the next line. Finally, stop recording the macro by pressing q again.
  7. The macro is now stored in a. Press @a to rerun the macro. Notice how it changes case and puts you on the next line.
  8. Press @a to run once more to complete the file.

  1. From a credit card statement ↩︎
Categorized as Vim Tagged