tags:

views:

98

answers:

2

If I have a data file with columns of numbers like

3.14
0.42
6.66

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

I can do it by piping to for instance awk, but I would like to know if there's a builtin method, and I haven't found anything in the help files.

+5  A: 

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.

Rod
Brilliant stuff, I hadn't even thought of using the expression register.
Sarah
Why not C<Ctrl-R>=<Ctrl-R>"+2.1<Enter> ?
Benoit
@Benoit. Sure works too. I updated my answer to remove the assign to register and make use of C.
Rod
Don't you mean " instead of *? Otherwise the system clipboard gunks it up.
Sarah
You are right. With my current config, on Windows, the * register is also mapped to the " register.
Rod
+2  A: 

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.
raja kolluru
Nice but won't work on Windows unless you also use Cygwin...
Rod
@Rod.. True you do need a cygwin. I proposed this since she had mentioned awk and hence I assumed that she had access to bc.
raja kolluru