Reputation: 5281
In vim, using regular expressions or patterns, how can a match be copied so that the match is put directly after itself, without replacing the match?
For example, I'd like to copy everything before a comma on a line, to after the comma:
one,
two,
three,
four,
... would then become:
one,one
two,two
three,three
four,four
I can match with .*,
, or globally with %s/.*,
. I can even do a zero-width match with .*,\@<=
or even .*,\zs
. But I can't figure out where to go from here.
Upvotes: 3
Views: 2637
Reputation: 7679
Use group capturing. To use group capturing, put part of your regex between parenthesis (they need to be escaped), then that will be placed in subgroup one. Everything in the next pair of parenthesis will be placed in subgroup two, etc. for up to 9 groups. You can then reference this group in the replace part of your substitution. For example:
:%s/\(.*\),/\1,\1
This means capture anything up to a comma, and call it group \1
. Then, replace this text with (group1),(group1)
. You could also do
:%s/\(.*\),/&\1
since &
means "The entire matched text" (same as \0).
You could also use very magic e.g. \v
to make this more readable. For example:
:%s/\v(.*),/&\1
As a side note, the simpler way to achieve the same affect would be to use :%norm
, which applies a set of keystrokes to every line. For example, you could do
:%norm yt,f,p
Recommended reading: http://vimregex.com/
Upvotes: 7