Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vim - Insert something between every letter

Tags:

vim

In vim I have a line of text like this:

abcdef

Now I want to add an underscore or something else between every letter, so this would be the result:

a_b_c_d_e_f

The only way I know of doing this wold be to record a macro like this:

qqa_<esc>lq4@q

Is there a better, easier way to do this?

like image 784
Mathias Begert Avatar asked Dec 15 '22 13:12

Mathias Begert


2 Answers

:%s/\(\p\)\p\@=/\1_/g

  • The : starts a command.
  • The % searches the whole document.
  • The \(\p\) will match and capture a printable symbol. You could replace \p with \w if you only wanted to match characters, for example.
  • The \p\@= does a lookahead check to make sure that the matched (first) \p is followed by another \p. This second one, i.e., \p\@= does not form part of the match. This is important.
  • In the replacement part, \1 fills in the matched (first) \p value, and the _ is a literal.
  • The last flag, g is the standard do them all flag.
like image 172
Caleb Hattingh Avatar answered Jan 16 '23 04:01

Caleb Hattingh


If you want to add _ only between letters you can do it like this:

:%s/\a\zs\ze\a/_/g

Replace \a with some other pattern if you want more than ASCII letters.

To understand how this is supposed to work: :help \a, :help \zs, :help \ze.

like image 42
lcd047 Avatar answered Jan 16 '23 02:01

lcd047