Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

Is it possible to format the replacement string when substituting a match with Vim?

Say I have a file with a 2-column table, where the entries in each row are separated with a space. The entries (and the lines) are not fixed width. I want to format the table such that the 2nd column items are all justified, by adding the appropriate amount of spaces.

For example, the given table:

A aa
BBBB bbb
CC c

What I want:

A      aa
BBBB   bbb
CC     c

(Please note that tabs are not a solution here.)

The Vim command may look something like:

:0,$ s/\(.*\) \(.*\)/\1(******N)\2/

and the (******N) should be replaced with the formatting code to put the 2nd element at the Nth character position.

UPDATE 1: So, Vim has the printf() function. Can it be used directly from the command prompt for that purpose, or does it have to be included in a Vim script, with an explicit loop running through all lines?

share|improve this question
up vote 5 down vote accepted

You may want to try one of the align plugins on I use the most popular one by Dr. Campbell:

That aside, though, yes, you can call Vim functions from a substitute command, but the drawback is that the entire replacement pattern has to be an expression. See ":help sub-replace-expression" and ":help submatch()". For example, if we wanted to replace a matched pattern with a letter count:


So your idea of using printf() would work:

:%s/\(.*\) \(.*\)/\=printf('%-7s %-7s',submatch(1),submatch(2))/
share|improve this answer

You didn't specify your system but, on UNIX-like systems, you can use the column command as a filter:

:%!column -t


:help filter
$ man column
share|improve this answer
Thanks. It is Windows. +1 - i assume it works on linux, and for thinking "out of the box" ;-) – ysap Mar 31 '14 at 7:57
Only a windows user could call that "thinking out of the box". – romainl Mar 31 '14 at 8:43
it was meant to be a little joke, referring to "going out of the Vim realm to the OS shell for doing the task". Note the ";-)". I am a Linux user as well, BTW... – ysap Mar 31 '14 at 9:31

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.