How do I apply a macro to every non-blank line in the file while skipping empty lines?
Answer
:g/./norm @q
Explanation
Combining the :global command with :normal lets you run a macro on every non-blank line in one shot. The pattern /. matches any line that has at least one character, which naturally excludes empty lines. This is far more efficient than counting lines or manually stopping when the macro hits a blank line, and it scales to files of any size without needing to specify a count.
How it works
:g— the global command; iterates over every line in the buffer/.— the match pattern;.matches any character, so this selects all non-empty linesnorm— short for:normal, executes normal-mode keystrokes for each matched line@q— plays back the macro stored in registerq; changeqto whichever register you used
Example
Suppose register q holds the keystrokes A,<Esc> (append a comma at the end of the line). Given this buffer:
apple
banana
cherry
Running :g/./norm @q produces:
apple,
banana,
cherry,
The empty lines are untouched.
Tips
- Replace
qwith any register name::g/./norm @auses macroa - Restrict to a subset of lines by changing the pattern:
:g/^def /norm @qruns only on lines starting withdef - To target blank lines instead, invert:
:g/^$/norm @q - Use
:g/./norm! @q(with!) to bypass custom key mappings during playback - Combine with a count to repeat the macro per line:
:g/./norm 3@q