Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to perform arithmetic manipulations on numbers in Vim?

Tags:

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.

like image 769
Sarah Avatar asked Sep 27 '10 20:09

Sarah


People also ask

How do you do arithmetic in Vim?

Vim can do some arithmetic for you. The simplest one are ctrl+a (add) and ctrl+x (subtract) actions. They find nearest digital number in the current line and add/subtract one to/from this number. You can prepend them with count to add/subtract more than one.

Which command is used to perform arithmetic?

Using let command let command is used to perform arithmetic operations.


2 Answers

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.

like image 80
Rod Avatar answered Sep 23 '22 04:09

Rod


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. 
like image 21
raja kolluru Avatar answered Sep 21 '22 04:09

raja kolluru