How do I increment or add to all numbers in a file using Vim substitution?
Answer
:%s/\d\+/\=submatch(0)+1/g
Explanation
Vim's expression replacement (\=) in substitutions lets you perform arithmetic on matched text. Combined with submatch(0), you can increment, decrement, multiply, or apply any mathematical transformation to every number in your file.
How it works
\d\+— matches one or more digits\=— evaluates the replacement as a Vimscript expressionsubmatch(0)— returns the matched text as a stringsubmatch(0)+1— Vim auto-converts the string to a number and adds 1
Example
:%s/\d\+/\=submatch(0)+1/g
Before: port 8080 and port 3000
After: port 8081 and port 3001
Multiply all numbers by 2:
:%s/\d\+/\=submatch(0)*2/g
Tips
- Use with a range:
:10,20s/\d\+/\=submatch(0)+100/g - For simple single-number increment/decrement, use
<C-a>and<C-x>in normal mode - Zero-pad results with
printf:\=printf('%03d', submatch(0)+1) - Combine with
:gto only increment numbers on specific lines