How do I zero-pad every number in a buffer with one substitution?
Answer
:%s/\v(\d+)/\=printf('%04d', submatch(1))/g
Explanation
When you need stable-width numeric fields, manual edits are slow and error-prone. This substitution uses Vim's expression replacement mode so each matched number is reformatted in place. It is especially useful in logs, fixture data, or migration files where mixed-width IDs break sorting and visual scanning.
How it works
:%s/\v(\d+)/\=printf('%04d', submatch(1))/g
:%sruns substitution across the entire buffer\venables very-magic regex mode, so\d+reads naturally as one-or-more digits(\d+)captures each numeric token\=switches replacement into expression modeprintf('%04d', submatch(1))converts the captured number to a 4-digit, zero-padded stringgapplies it to every match on each line
Example
Before:
item-7
item-42
item-103
After:
item-0007
item-0042
item-0103
Tips
- Change
%04dto%06d(or any width) for different padding requirements - Use a narrower pattern if you only want specific number positions transformed
- Add the
cflag when you want interactive confirmation per match