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

How do I search for a pattern only within a specific range of lines in Vim?

Answer

:/start/,/end/s/pattern/replacement/g

Explanation

You can restrict a substitution to a range defined by two patterns. This is useful when you want to make changes only within a specific section of a file, such as between two headings or markers.

How it works

  • :/start/,/end/ defines a range from the line matching start to the line matching end
  • s/pattern/replacement/g performs the substitution only within that range
  • The range patterns are regular expressions, just like the substitution pattern

Example

Suppose you have a config file and want to change debug to info only in the [logging] section:

[server]
debug = true

[logging]
debug = verbose
level = debug

[database]
debug = false

Running :/\[logging\]/,/\[/s/debug/info/g changes only the logging section:

[server]
debug = true

[logging]
info = verbose
level = info

[database]
debug = false

Tips

  • You can also use line numbers: :10,20s/old/new/g
  • Use \%V in the search pattern to restrict to the last visual selection
  • Add c flag for confirmation: :/start/,/end/s/pattern/replacement/gc

Next

How do I visually select a double-quoted string including the quotes themselves?