How do I use marks to define a range for Ex commands?
Answer
:'a,'b s/old/new/g
Explanation
Marks can be used as range specifiers in any Ex command. The syntax 'a,'b defines a range from the line containing mark a to the line containing mark b, letting you operate on precisely defined regions of your file.
How it works
- Set mark
aat the start of your region:ma - Navigate to the end of the region and set mark
b:mb - Run any Ex command with the range
'a,'b
Examples
" Substitute within marked range
:'a,'b s/foo/bar/g
" Delete all lines between marks
:'a,'b d
" Indent lines between marks
:'a,'b >
" Sort lines between marks
:'a,'b sort
" Run normal mode command on marked range
:'a,'b normal A;
" Yank marked range into register
:'a,'b y z
Special mark ranges
" From mark a to current line
:'a,. s/old/new/g
" From mark a to end of file
:'a,$ d
" From beginning of file to mark b
:1,'b s/old/new/g
Tips
- Visual mode automatically sets marks
'<and'>, which is why:'<,'>appears when you type:in visual mode - Use backtick marks (
`a,`b) for character-precise ranges instead of line-based - This technique is essential for operating on non-contiguous, logically related sections of code