How do I run a normal mode command on multiple lines at once?
Answer
:'<,'>norm! A;
Explanation
The :normal Ex command lets you execute any Normal mode keystrokes on a range of lines simultaneously, turning a single-line operation into a multi-line batch edit without recording a macro. Combined with a visual selection range, it becomes a precise and powerful bulk editing tool.
How it works
:'<,'>— the range spanning the last visual selection (automatically inserted when you press:while in Visual mode)norm!— run Normal mode keystrokes literally, bypassing any custom key remappings (the!ensures consistent, portable behavior)A;— the Normal mode command to execute on each line:Aenters Insert mode at end of line,;types the character, and Vim then exits back to Normal mode
You can substitute any Normal mode sequence for A;. Common examples:
I#— prepend#to comment out lines>>— indent each line one leveldw— delete first word on each line
Example
Given three lines selected with V:
foo()
bar()
baz()
Running :'<,'>norm! A; transforms every line:
foo();
bar();
baz();
Tips
- Works with any line range:
:1,$norm! >>indents the entire file - Use
norm(no!) only when you intentionally want custom mappings to fire - Pair with
:g/pattern/norm! commandto run Normal commands only on lines matching a pattern