How do I zero-pad or reformat numbers during a substitution using printf in Vim?
Answer
:%s/\d\+/\=printf('%03d', submatch(0))/g
Explanation
Combining Vim's \= expression substitution with the printf() function lets you apply arbitrary formatting to matched text. This is particularly useful for zero-padding numbers so they sort lexicographically — for example, normalizing file1, file2, file10 into file001, file002, file010.
How it works
\d\+matches one or more digits\=tells Vim the replacement is a Vimscript expressionprintf('%03d', submatch(0))formats the matched digits:%03dmeans an integer padded with leading zeros to at least 3 digitssubmatch(0)returns the full match (equivalent to&in a plain replacement)
Example
Given:
file1.txt file2.txt file10.txt
After :%s/\d\+/\=printf('%03d', submatch(0))/g:
file001.txt file002.txt file010.txt
Tips
- Use
'%05d'for five-digit padding, or'%04d'for four. printf()follows C-style format specifiers:%sfor strings,%ffor floats,%xfor hex.- Combine with capture groups via
submatch(1),submatch(2)etc. for more complex transformations. - To convert to uppercase while reformatting:
\=printf('%s', toupper(submatch(0)))