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.
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.
Using let command let command is used to perform arithmetic operations.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With