How to perform arithmetic manipulations on numbers in Vim?

A useful feature, which happens to be convenient in this case, is substitution with an expression (see :help sub-replace-\=). It allows to evaluate an expression on every pattern match of a substitute command and replace the matched text with the result of that expression.

For example, to add, say, 2.1 to all values in the third column of a tab-separated file, one can use the following command.

:%s/^\%([^\t]*\t\)\{2}\zs[^\t]*/\=str2float(submatch(0))+2.1/

Expression registers are great with vim.

Here is a more old fashioned vi way to doing this: Let us say you have a file containing a bunch of numbers one in each line and you want to add 2.1 to each of the lines.

:%s/$/+2.1/<ENTER> - this would append +2.1 to each line.
:1<ENTER>  - Goto the beginning of the file 
!Gbc<ENTER> - invoke the bc command on each line to do the addition.

Use CTRL-R with the expression register =.

The following command would add 2.1 to a number on a line:

C
<CTRL-R> =
<CTRL-R> "
+2.1
<ENTER>

Combine with macro it can yield some interesting results, such as this example.

Tags:

Vim