简体   繁体   中英

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?

:%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, ie, \\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.

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 .

Use positive lookahead and substitute:

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

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM