DEV Community

Sérgio Araújo
Sérgio Araújo

Posted on

Vim: Using math in substitution

Vim: Calculating age in substitution

Let's say you have:
source: https://sanctum.geek.nz/arabesque/advanced-vim-macros/

    Stallman   Richard   GNU    1953  USA
    Wall       Larry     Perl   1954  USA
    Moolenar   Bram      Vim    1961  Netherlands
    Tridgell   Andrew    Samba  1967  Australia
    Matsumoto  Yukihiro  Ruby   1965  Japan
    Ritchie    Dennis    C      1941  USA
    Thompson   Ken       Unix   1943  USA
Enter fullscreen mode Exit fullscreen mode

and you want to calculate how old each of these guys above
is right now:

My solution with no macros:

    :%s,\d\+,\=strftime("%Y")-submatch(0)
Enter fullscreen mode Exit fullscreen mode
    Stallman   Richard   GNU    66  USA
    Wall       Larry     Perl   65  USA
    Moolenar   Bram      Vim    58  Netherlands
    Tridgell   Andrew    Samba  52  Australia
    Matsumoto  Yukihiro  Ruby   54  Japan
    Ritchie    Dennis    C      78  USA
    Thompson   Ken       Unix   76  USA
Enter fullscreen mode Exit fullscreen mode

Tip 1: Use Regular Expressions to match the numbers

\d\+ means: find a digit or more. That regex matches exactly our fourth column

Tip 2: Exchange Delimiter

In my case typing comma is much easier than typing slash, so I have exchanged the substitution delimiter.

Tip 3: Not always we need the global substitution

In our case we just need the substitution once, so we omitted the final coma plus 'g'

Tip 4: Use expression register in substitution

In order to use expression register in substitution just type \=

Tip 5: To get current year

We are using strftime("%Y")

Tip 6: Submatch(0)

It matches the pattern we just referred on the search part of the substitution

For more information use the vim help system:
:h regex
:h \=
:h submatch
:h strftime

Oldest comments (2)

Collapse
 
moopet profile image
Ben Sinclair

I never knew about submatches like that. Thanks!

Collapse
 
voyeg3r profile image
Sérgio Araújo

The mentioned reference teaches us how to solve the same issue using macros: sanctum.geek.nz/arabesque/advanced...