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

How do I zero-pad every number in a line using a Vim substitute expression?

Answer

:s/\v\d+/\=printf('%04d', submatch(0))/g

Explanation

Substitution expressions let Vim compute each replacement dynamically, which is ideal when plain capture groups are too limited. This command finds every number on the current line and rewrites it as a zero-padded 4-digit value. It is useful for normalizing IDs, counters, or log fields without opening external tools.

How it works

  • :s/.../.../g runs substitution on the current line and applies it to all matches (g).
  • \v\d+ uses very-magic mode to match one or more digits.
  • \= tells Vim the replacement is an expression, not literal text.
  • printf('%04d', submatch(0)) formats the full match as a 4-digit decimal with leading zeroes.

Example

Starting line:

build=7 retry=42 shard=305

Run:

:s/\v\d+/\=printf('%04d', submatch(0))/g

Result:

build=0007 retry=0042 shard=0305

Tips

  • Use % range (:%s/.../.../g) to normalize an entire file.
  • Change %04d to %06d (or any width) to match your target format.
  • If numbers may be negative, switch the pattern to \v-?\d+.

Next

How do I launch a GDB session in Vim with the built-in termdebug plugin?