Macros are a sequence of commands recorded to a register.
Recording a macro:
Type the q key followed by the register.
I.e: To start recording a macro in the register a, type: q a
You should see a message in the status line at the bottom of the VIM: recording @a
To stop recording a macro, just type q.
To check what is recorded in the register @a
for example, you can type:
:reg a
To replay a macro that is recorded on register a, type @ a , you can also use @ @ to repeat the last macro used.
Macro best practices
- Normalize the cursor position: 0
- Perform edits and operation
- Position your cursor to enable easy replays: j
TIP:
You can apply the macro to multiple line using count.
I.e: Applying the macro to the next 5 lines {count}{@}{macro} : 5 @ a
Example using Macros
Let's say you having the following text:
1 FIRST NAME: Joseph LAST NAME: Andrews
2 FIRST NAME: Scott LAST NAME: Young
3 FIRST NAME: Jessica LAST NAME: Smith
4 FIRST NAME: Shirley LAST NAME: Landers
5 FIRST NAME: Pamela LAST NAME: Lewis
And you want to remove FIRST NAME: and LAST NAME, the result should be:
1 Joseph Andrews
2 Scott Young
3 Jessica Smith
4 Shirley Landers
5 Pamela Lewis
Steps
- Start recording a macro at register b: q b
- Position the cursor at the first character in the line: 0
- Delete the first 2 words: 2 d W
- Move your cursor to the next word: W
- Repeat the last operation: .
- Move your cursor to the next line: j
- Stop recording: q
- Apply the macro to the next 4 lines: 4 @ b
Or you could use global command:
:g/\(FIRST\|LAST\) NAME: /norm 2dWW.
Top comments (0)