Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vim search and replace, adding a constant

I know this is a long shot, but I have a huge text file and I need to add a given number to other numbers matching some criteria.

Eg.

identifying text 1.1200
identifying text 1.1400

and I'd like to transform this (by adding say 1.15) to

identifying text 2.2700
identifying text 2.2900

Normally I'd do this in Python, but it's on a Windows machine where I can't install too many things. I've got Vim though :)

like image 733
Internet man Avatar asked Nov 16 '10 11:11

Internet man


People also ask

How do I search and replace in Vim?

Basic Find and Replace In Vim, you can find and replace text using the :substitute ( :s ) command. To run commands in Vim, you must be in normal mode, the default mode when starting the editor. To go back to normal mode from any other mode, just press the 'Esc' key.

How do you replace a word with another word in Vim?

Search for text using / or for a word using * . In normal mode, type cgn (change the next search hit) then immediately type the replacement. Press Esc to finish. From normal mode, search for the next occurrence that you want to replace ( n ) and press . to repeat the last change.


1 Answers

Here is a simplification and a fix on hobbs' solution:

:%s/identifying text \zs\d\+\(.\d\+\)\=/\=(1.15+str2float(submatch(0)))/

Thanks to \zs, there is no need to recall the leading text. Thanks to str2float() a single addition is done on the whole number (in other words, 1.15 + 2.87 will give the expected result, 4.02, and not 3.102).

Of course this solution requires a recent version of Vim (7.3?)

like image 80
Luc Hermitte Avatar answered Oct 25 '22 01:10

Luc Hermitte