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

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
  • :%s runs substitution across the whole buffer
  • \d\+ matches each number (one or more digits)
  • \= tells Vim to evaluate the replacement as an expression
  • submatch(0) returns the full matched number
  • printf('%04d', ...) formats it as a 4-digit zero-padded integer
  • g applies 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 %04d to %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

Next

How do I jump to the top of a file without creating a new jumplist entry?