Mathias Begert
Mathias Begert

Reputation: 2471

Vim - Insert something between every letter

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?

Upvotes: 4

Views: 2491

Answers (5)

eacmacro
eacmacro

Reputation: 1

:%s/../&:/g

This will add ":" after every two characters, for the whole line. The first two periods signify the number of characters to be skipped. The "&" (from what I gathered) is interpreted by vim to identify what character is going to be added. Simply indicate that character right after "&" "/g" makes the change globally. I haven't figured out how to exclude the end of the line though, with the result being that the characters inserted get tagged onto the end...so that something like:

"c400ad4db63b"

Becomes "c4:00:ad:4d:b6:3b:"

Upvotes: 0

glts
glts

Reputation: 22684

Here's a quick and a little more interactive way of doing this, all in normal mode.

With the cursor at the beginning of the line, press:

  1. i_<Esc>x to insert and delete the separator character. (We do this for the side effect.)
  2. gp to put the separator back.
  3. ., hold it down until the job is done.

Unfortunately we can't use a count with . here, because it would just paste the separator 'count' times on the spot.

Upvotes: 2

Caleb Hattingh
Caleb Hattingh

Reputation: 9225

:%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.

Upvotes: 5

lcd047
lcd047

Reputation: 5851

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.

Upvotes: 4

Arunesh Singh
Arunesh Singh

Reputation: 3535

Use positive lookahead and substitute:

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

This will match any character followed by any character except line break.

Upvotes: 2

Related Questions