Substitution in Vim using the capture sequence

48 Views Asked by At

I have the following lines in my text file:

.abc(),
.def(),
.ghi(),
.jkl(),

and I'd like to transform them into this:

.abc(abc),
.def(def),
.ghi(ghi),
.jkl(jkl),

I've tried :%s/\.\(\w\+\)(\),/.\1(\1),/g but it won't take.

1

There are 1 best solutions below

0
romainl On

The problem is this backslash:

:%s/\.\(\w\+\)(\),/.\1(\1),/g
               ^

which is ambiguous as the capture group has already been closed. Because of that, your patten doesn't match and your substitution does nothing.

Removing it makes your substitution work:

:%s/\.\(\w\+\)(),/.\1(\1),/g

Now, the complexity of that substitution may be required by the actual content of the actual file but it doesn't fit your sample.

  • The parts that don't change before and after the parts that change can be removed:

    :%s/\(\w\+\)(/\1(\1,/g
    
  • Since there is only one match on each line, the /g is useless:

    :%s/\(\w\+\)(/\1(\1