Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In vim I want to find a string and insert spaces in between each character of the string

I have been trying to search and replace with regex and capture groups in a simple way, but have no idea how.

Let's say I want to operate on the previous sentence capturing "trying" and replacing with "t r y i n g".

:%s/\vtrying{-}/ \1/g
like image 345
Clay Morton Avatar asked Sep 16 '15 04:09

Clay Morton


People also ask

How do I add text to the end of a line in vi?

Type A to add text to the end of a line. To see how this command works, position the cursor anywhere on a text line and type A . The cursor moves to the end of the line, where you can type your additions. Press Esc when you are finished.


2 Answers

You have a solution, but here is a different one:

 %s/trying/\=join(split(submatch(0),'\zs'), ' ')/g

That should be a little bit faster than the substitute() call, not that this matters much.

like image 87
Christian Brabandt Avatar answered Sep 19 '22 15:09

Christian Brabandt


Just do two substitute matches. Where the second one uses the substitute with an expression (\= at the beginning of the replacement :h sub-replace-expression)

:%s/trying/\=substitute(submatch(0), '\w\zs\ze\w', ' ', 'g')/

The expression just inserts a space between every word character.

like image 45
FDinoff Avatar answered Sep 20 '22 15:09

FDinoff