Sarah
Sarah

Reputation: 6695

How to perform arithmetic manipulations on numbers in Vim?

If I have a data file with columns of numbers like

3.14
0.42
6.66

Is there a way from within Vim to manipulate these with operations such as addition, subtraction, and division? For instance, say I want to add 2.1 to each number in a column, how should I go about this?

I can do it by piping to, for instance, an Awk script, but I would like to know if there is a builtin method, and I haven’t found anything in the help files.

Upvotes: 35

Views: 16076

Answers (3)

ib.
ib.

Reputation: 28934

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/

Upvotes: 6

Rod
Rod

Reputation: 55752

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.

Upvotes: 45

Raja Shankar Kolluru
Raja Shankar Kolluru

Reputation: 602

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.

Upvotes: 7

Related Questions