How do I zero-pad every number in a buffer using one substitute expression?
Answer
:%s/\d\+/\=printf('%04d', submatch(0))/g
Explanation
When you need fixed-width numeric fields, manually editing each number is slow and error-prone. Vim can transform every match in one pass by evaluating an expression for each replacement. This is especially useful when preparing logs, IDs, or aligned output for scripts that expect zero-padded numbers.
How it works
:%s/\d\+/\=printf('%04d', submatch(0))/g
:%sruns substitution across the whole buffer\d\+matches each number (one or more digits)\=tells Vim to evaluate the replacement as an expressionsubmatch(0)returns the full matched numberprintf('%04d', ...)formats it as a 4-digit zero-padded integergapplies the substitution to every number on each line
Example
Before:
Error 7 on line 42
Build 3 done
After:
Error 0007 on line 0042
Build 0003 done
Tips
- Change
%04dto%06d(or another width) for different padding - Restrict scope by replacing
%with a visual range or line range - Because this uses expression replacement, you can also perform arithmetic or conditional formatting in the replacement step