Search code examples
vimmacrossubstitution

Various ways of substitution in Vim


How would you do to turn this

Dragon.Ball.026.C'est.la.finale.!!.Kame.hame.ha.mkv
Dragon.Ball.027.Goku...Le.moment.le.plus.critique.mkv
Dragon.Ball.028.Impact.!!.La.puissance.contre.la.puissance.mkv
Dragon.Ball.029.A.nouveau,.l'aventure..Le.lac.errant.mkv
Dragon.Ball.030.Pilaf.et.l'armée.mystérieuse.mkv

into this

Dragon.Ball.026.mkv
Dragon.Ball.027.mkv
Dragon.Ball.028.mkv
Dragon.Ball.029.mkv
Dragon.Ball.030.mkv

I succeeded with difficulty with a macro, but there may be a simple way ? (substitution, block mode, macro or anything else..)

It's for my personal knowledge,

Regards.


Solution

  • You can remember parts of a match with capture groups: \( and \). So match and remember everything up to the last digit \d, plus the rest of the line .* (but don't remember this part), and use \1 to put back the remembered part of the line, and manually add the extension .mkv:

    :%s/\(.*\d\).*/\1.mkv
    

    See :help pattern-searches, :help pattern-atoms and in particular :help \(

    Note

    You could also remember the extension with a second capture group and add it back like with \2:

    :%s/\(.*\d\).*\(\.mkv\)/\1\2