Vim - insert anything between each letter
In vim, I have a line of text like this:
abcdef
Now I want to add an underline or something between each letter, so this will be the result:
a_b_c_d_e_f
The only way I know to do this is to write the macro like this:
qqa_<esc>lq4@q
Is there a better, easier way to do this?
Here's a quick and slightly more interactive way to do it, everything is normal.
With the cursor at the beginning of the line, press:
-
i_<Esc>x
to insert and remove the separator character. (We do this for a side effect.) -
gp
to return the separator. -
.
, hold it until the job is done.
Unfortunately, we cannot use a counter with .
here, because it simply inserts the "count" delimiters in place.
If you _
only want to add between letters, you can do it like this:
:%s/\a\zs\ze\a/_/g
Replace with \a
another pattern if you want more than ASCII letters.
To understand how this should work: :help \a
, :help \zs
, :help \ze
.
:%s/\(\p\)\p\@=/\1_/g
-
:
runs the command. -
%
searches the entire document. -
\(\p\)
will match and freeze the character for printing. You could replace\p
with\w
if you just wanted to match characters, eg. -
\p\@=
performs a audit trail to ensure that a match (first) is\p
followed by another\p
. This second, i.e.\p\@=
is not part of the match. It is important. - In the replacement part,
\1
fills in the matching (first) value\p
, and_
a literal. - The last flag
g
is the standard for all flags.
Use positive and replace:
:%s/\(.\(.\)\@=\)/\1_/g
This will match any character followed by any character except line break
.