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 matchingstartto the line matchingends/pattern/replacement/gperforms 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
\%Vin the search pattern to restrict to the last visual selection - Add
cflag for confirmation::/start/,/end/s/pattern/replacement/gc