Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to conditionally replace numbers using vim

I can see a lot of discussion on how to replace strings conditionally using :%s. But I want to do exactly this in my file that has a huge bunch of numbers in a CSV format:

  1. Find numbers < -100
  2. Replace them by -98

How can I do this in VIM or any other editor/script language?

like image 684
Badri Narayanan Gopalakrishnan Avatar asked Mar 13 '26 01:03

Badri Narayanan Gopalakrishnan


1 Answers

It is possible using the submatch() function like this:

:%s/-[0-9]\+/\=submatch(0) < -100 ? -98 : submatch(0)/g

Now every number smaller than -100 will be replaced by -98 and the rest just stays the same. Note that this regex will only match negative numbers.

like image 132
Sander Vanhove Avatar answered Mar 15 '26 18:03

Sander Vanhove



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!