elsonwx elsonwx - 5 months ago 8
Linux Question

vim regular replace,how to replace the old str with old str+appended str

this is the text in my vim

enter image description here

I want to change it to the content as next using regular,

enter image description here

I have try

:%s/^.*$/\g<0>,\g<0>/g
,it's no working..

Answer

You can achieve that with the following replacement:

:%s/^.*$/&,&/g
         ^ ^ 

The ^.*$ pattern will match the whole line, and & is a backreference to the whole match. So, the replacement is inserting back the whole match, a comma, and again the whole match.

NOTE: The ^ and $ in this ^.*$ pattern can be omitted, but a lot of people prefer to keep them explicit in the pattern to facilitate pattern readability and further pattern testing.

An alternative in case you want to avoid matching empty lines:

:%s/.\+/&,&/g
    ^^^

The .\+ will match 1 or more characters.

Comments