Vim/Recording And Replaying Macros

From Debuntu

< Vim
Jump to: navigation, search

Vim allows you to record a sequence of actions that you perform on a line and replay them on a chosen number of lines.

As an example, we are going to create 10 lines containing "line number X" where X is the number of the line by only:

Finally, we will comment out those 10 line by:

Creating the 10 lines

  1. Open a file called 10lines.txt:
    vi 10lines.txt
  2. Enter Insert mode and type line number 1
    Iline number 1
  3. Start recording macro a:
    Escqa
  4. Create the macro:
    • Copy the line (yy)
    • Paste it (p)
    • move to the end of the line ($)
    • increment the number by one (Ctrl-A)
  5. Stop the recording of the macro:
    q
  6. Replay the macro 8 times:
    8@a

You should now have the following text in vi:

line number 1
line number 2
line number 3
line number 4
line number 5
line number 6
line number 7
line number 8
line number 9
line number 10

Commenting the 10 lines

To comment the 10 lines, we will go back to the beginning of the file, start recording, comment out the first line and then replay this on the next 9 line. Here is the sequence:

  1. Go to the top of the file (gg)
  2. start recording macro b (qb)
  3. Go to the beginning of the line and enter insert mode (I)
  4. Type your commenting character, here we take ;; as a comment (;;)
  5. Enter escape mode (Esc)
  6. Go to next line (j)
  7. Stop the recording (q)
  8. replay it 9 times (9@b)

Your text should now look like:

;;line number 1
;;line number 2
;;line number 3
;;line number 4
;;line number 5
;;line number 6
;;line number 7
;;line number 8
;;line number 9
;;line number 10
Personal tools
Namespaces
Variants
Actions
Navigation
Toolbox
Google AdSense