vimtricks.wiki Concise Vim tricks, one at a time.

How do I restrict a substitution to the range between two named marks?

Answer

:'a,'bs/old/new/g

Explanation

Named marks can serve as range endpoints for any Ex command, including :substitute. Setting two marks at the boundaries of a region lets you confine a substitution to just those lines — even after you've moved the cursor elsewhere. This is more flexible than a visual selection because marks persist until you explicitly change them.

How it works

  • m{a-z} — set a lowercase mark at the current line
  • 'a in a range — refers to the line where mark a was set
  • 'a,'b — the range from mark a to mark b (inclusive)
  • The substitution only runs on lines within this range

Example

Suppose you have a function and want to rename localVar to count only inside it:

function setup() {
    localVar = 0
    localVar += 1
    localVar *= 2
}

localVar = 99  ← outside function
  1. Move to the function line, press ma
  2. Move to the closing } line, press mb
  3. Run :'a,'bs/localVar/count/g

Result:

function setup() {
    count = 0
    count += 1
    count *= 2
}

localVar = 99  ← unchanged

Tips

  • Works with any Ex command: :'a,'bd deletes lines, :'a,'b> indents them
  • Combine with :g: :'a,'bg/pattern/d deletes matching lines only within the marked region
  • Use `a (backtick) instead of 'a (single-quote) to operate at the exact column, not just the line
  • Marks survive across buffer switches, making this useful for cross-session edits

Next

How do I get just the filename without its path or extension to use in a command?