Skip to content

Incrementing alpha strings with Vim

TL;DR: Need to increment a MAC address (for example) in Vim? Do this::set nf=octal,hex,alpha
Now put the cursor over the 2nd char of the octet pair and press <CTRL-A> to increment. Add the ‘set‘ line to your .vimrc for permanence.

What do you do when you need to increment a MAC address in a config file (and don’t care to write some fancy parser in Perl or something)?

I ran into this need because we have servers with two ethernet interfaces, however we only have the MAC addresses for the first (eth0).  Knowing that they are numbered consecutively (eth1′s MAC is “one more” than eth0) we simply have to increment the last octet of the known (first) MAC.

The problem is that Vim defaults to increment/decrement only acting on numbers — MACs, being hex and therefore [potentially] containing alphabetical characters, don’t increment “correctly” without some tweaking of your Vim settings.

Let’s get to it

It’s quite simple, just instruct Vim to treat letters as part of a number format, and incrementing / decrementing will handle letters as well. This is accomplished by setting the ‘nrformats‘ (or ‘nf‘ for short):

:set nf=octal,hex,alpha

Now pressing <CTRL-A> will increment ‘a’ to ‘b’, as well as continue to increment ’5′ to ’6′, as before.  <CTRL-X> decrements.
So, using the MAC incrementing as an example, if you have “00:30:48:34:b9:9e” (cursor over the ‘e’) and press <CTRL-A>, you will get “00:30:48:34:b9:9f“.

If you want to make this a permanent feature, just add a set nf=octal,hex,alpha line to your ~/.vimrc file.

Caveats

This does change the behavior of <CTRL-A> and <CTRL-X> slightly (beyond the obvious).  With the defaults (nf=octal,hex), If you have ‘foo123′ (cursor over the ‘f’) and press <CTRL-A>, you will end up with ‘foo124‘.  If you change the nf setting as described, you will end up with ‘goo123′.  So, it’s important that you are more precise with your cursor placement.  This could be of particular concern when combining this with Vim macros.

Also, Vim is not as ‘smart’ as Perl (or any other language that you might like).  You can’t increment past ‘z’ or ‘Z’ (not a problem with MACs, but your use case my be different), nor decrement before ‘a’ or ‘A’.  If you expect either of those things to work, you’ll have to write a parser in a more powerful language to do what you expect.

-jv