Reputation: 2471
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
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
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:
i_<Esc>x
to insert and delete the separator character. (We do this for the side effect.)gp
to put the separator back..
, 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
Reputation: 9225
:%s/\(\p\)\p\@=/\1_/g
:
starts a command.%
searches the whole document.\(\p\)
will match and capture a printable symbol. You could replace \p
with \w
if you only wanted to match characters, for example.\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.\1
fills in the matched (first) \p
value, and the _
is a literal.g
is the standard do them all flag.Upvotes: 5
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
Reputation: 3535
Use positive lookahead and substitute:
:%s/\(.\(.\)\@=\)/\1_/g
This will match any character followed by any character except line break
.
Upvotes: 2