Vim: Substitute a String with Characters Equal to the Length of the String

23 Nov 2016

If you wanted to replace:

hello

With characters equal to the length of this string(without hardcoding):

-----

Then you you will need to use a sub-replace-expression (\=) inside your substitution.

To get the above result, run the following in vim command-line mode:

:s/hello/\=repeat('-', strlen(submatch(0)))/

Breaking this down, we are using the :substitute expression, and using \= in the string area to make it a sub-replace-expression, so that Vimscript can be executed. The repeat function takes the first argument character and returns a string whose length is determined by the second argument: repeat('-', 5) returns -----

submatch is a special substitute-only function that refers to patterns. submatch(0) refers to to the entirety of the matched pattern. [1] strlen returns the length of that string. Which means in this case strlen(submatch(0)) returns 5.


This formula is very useful for mass replacing reStructuredText headers.

If you wanted to replace:

foo
---

otter-pop

barz
----

You could use something like:

%s/-\{2,\}/\=repeat('=', strlen(submatch(0)))/c

To greedily match the hypen-headers while avoiding single hypens, and get one confirmation for the whole header. If you do not greedily match the hypens, then vim will ask for confirmation of each header hypen, and not the group. the sub-replace-expression allows for the greedy expression to match the correct number of characters.

For more information, see:

[1]Other numbers refer the patterns grouped by parenthesis see :h \(\).

Comments !