Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to multiply with vim

Tags:

vim

I have a CSS file where everything is slightly too large, so I want to replace every occurrence of $size px by $size*0.75 px (for example 100px to 75px and so on).

How do I do that with vim? Is it even possible?

like image 593
iblue Avatar asked Nov 21 '15 15:11

iblue


2 Answers

This command may give you a hand:

%s/\d\+\ze\s*px/\=float2nr(submatch(0)*0.75)/g

This will change:

200 px
100px
777px

into:

150 px
75px
582px

add explanation

This is a :s command, we first find the numbers before the px, in replacement part, I used replacement expression, which does the calculation. The submatch(0) will reference the numbers we just found. float2nr() function is just for getting integer result.

In vim :h :s :h \ze and :h sub-replace-expression there are very detailed explanations

like image 61
Kent Avatar answered Oct 19 '22 10:10

Kent


Don't forget about the expression register where you can do simple arithmetic: http://vimcasts.org/episodes/simple-calculations-with-vims-expression-register/

Vim commands and effects

like image 43
Jonathan.Brink Avatar answered Oct 19 '22 08:10

Jonathan.Brink