Take the 2-minute tour ×

I have this column in a file I'm editing in VIM:

# etc...

And I want to convert it to this column:

# etc...

How can I do this in VIM?

share|improve this question
add comment

5 Answers

up vote 18 down vote accepted

Use printf (analogous to C's sprintf) with the \= command to handle the replacement:

:%s/\d\+/\=printf("0x%04x", submatch(0))


  • :%s/\d\+/ : Match one or more digits (\d\+) on any line (:%) and substitute (s).
  • \= : for each match, replace with the result of the following expression:
  • printf("0x%04x", : produce a string using the format "0x%04x", which corresponds to a literal 0x followed by a four digit (or more) hex number, padded with zeros.
  • submatch(0) : The result of the complete match (i.e. the number).

For more information, see:

:help printf()
:help submatch()
:help sub-replace-special
:help :s
share|improve this answer
+1 nice (... and the remaining 15 characters) –  stefanB Jul 21 '09 at 1:53
add comment

Yet another way:

:rubydo $_ = '0x%x' % $_


:perldo $_ = sprintf '0x%x', $_

This is a bit less typing and you avoid a level of quoting / shell escaping that you'd get if you did this via :!. You need Perl / Ruby support compiled into your Vim.

share|improve this answer
And it's easier than remembering how to use Vimscript, if (like most people) you use it far less often than Perl and Ruby. –  ephemient Jul 14 '09 at 4:27
add comment

another way, to pass it to awk

awk '{printf "0x%x\n",$1}' file
share|improve this answer
add comment

Select (VISUAL) the block of lines that contains the numbers, and then:

:!perl -ne 'printf "0x\%x\n", $_'
share|improve this answer
Why use perl when Vim has an internal printf? –  DrAl Jul 13 '09 at 10:07
add comment

Convert decimal to hex

share|improve this answer
This is a bit redundant in recent Vim's as there is a printf function. Very useful in Vim 6.x though! –  DrAl Jul 13 '09 at 10:19
Thanks for the info, Al. Looks like its time to refresh my vim knowledge. –  Brandon E Taylor Jul 13 '09 at 14:42
add comment

Your Answer


