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

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/.../.../g runs 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 expression
  • printf('%04d', submatch(0)) formats the matched number to width 4, left-padding with zeroes
  • submatch(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 %04d to %06d (or any width) to match your target format
  • You can adapt the expression for hex, trimming, or arithmetic transforms during replacement

Next

How do I uppercase text inside an HTML tag without changing the tags?