Vim/Recording And Replaying Macros
From Debuntu
< Vim
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:
- Creating the first line
- recording the macro to create the second line
- replaying the macro for the 8 other lines
Finally, we will comment out those 10 line by:
- Go to the first line
- start the recording
- comment the line
- stop the macro
- replay the macro for the next 9 lines.
Creating the 10 lines
- Open a file called 10lines.txt:
- vi 10lines.txt
- Enter Insert mode and type line number 1
- Iline number 1
- Start recording macro a:
- Escqa
- Create the macro:
- Copy the line (yy)
- Paste it (p)
- move to the end of the line ($)
- increment the number by one (Ctrl-A)
- Stop the recording of the macro:
- q
- 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:
- Go to the top of the file (gg)
- start recording macro b (qb)
- Go to the beginning of the line and enter insert mode (I)
- Type your commenting character, here we take ;; as a comment (;;)
- Enter escape mode (Esc)
- Go to next line (j)
- Stop the recording (q)
- 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