vimtricks.wiki Concise Vim tricks, one at a time.

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
  • :%s runs substitution across the entire buffer
  • \v enables very-magic regex mode, so \d+ reads naturally as one-or-more digits
  • (\d+) captures each numeric token
  • \= switches replacement into expression mode
  • printf('%04d', submatch(1)) converts the captured number to a 4-digit, zero-padded string
  • g applies it to every match on each line

Example

Before:

item-7
item-42
item-103

After:

item-0007
item-0042
item-0103

Tips

  • Change %04d to %06d (or any width) for different padding requirements
  • Use a narrower pattern if you only want specific number positions transformed
  • Add the c flag when you want interactive confirmation per match

Next

How do I regenerate help tags for every installed plugin in one command?