How do I convert all numbers to fixed-width zero-padded values in Vim?
Answer
:%s/\v\d+/\=printf('%04d', submatch(0))/g
Explanation
When you need aligned numeric data for logs, IDs, or generated fixtures, manual edits are slow and error-prone. Vim's expression replacement lets you compute each replacement dynamically during substitution. Using printf() inside :s gives deterministic, fixed-width formatting across the entire buffer in one pass.
How it works
:%s/.../.../gruns substitution globally across every line in the file\v\d+uses very-magic mode and matches one or more digits\=tells Vim to evaluate the replacement as an expressionprintf('%04d', submatch(0))formats the matched number to width 4, left-padding with zeroessubmatch(0)returns the full match for each numeric token
This pattern scales well when editing structured text where numeric width consistency matters.
Example
Before:
item_7
item_42
item_305
Run:
:%s/\v\d+/\=printf('%04d', submatch(0))/g
After:
item_0007
item_0042
item_0305
Tips
- Change
%04dto%06d(or any width) to match your target format - You can adapt the expression for hex, trimming, or arithmetic transforms during replacement