rs1
rs1

Reputation: 167

vi: is there a way to manipulate regex matches?

I have a file with the following line:

img width="240" height="120"

I want to scale the width and height by the same amount so

:%s/width="\\(.*\\)" height="\\(.*\\)"/width="2*\\1" height="2*\\2"/g

produces

img width="2*240" height="2*120"

is there anyway to make vi actually compute 2*240=480 and put 480 in the result.

thanks for your help.

Upvotes: 3

Views: 103

Answers (2)

Danilo Piazzalunga
Danilo Piazzalunga

Reputation: 7802

I can get something close to what you ask with

:s/\(\d\+\)/\=submatch(1)*2/gc

But I would use an external filter.

Upvotes: 4

William Pursell
William Pursell

Reputation: 212298

I would typically use an external filter for that sort of thing:

:%!perl -pe 's/width="(\d*)"/sprintf "width=\"\%d\"", 2 * $1/e'

Note that there is an additional escape there that would not appear when running perl directly. You must escape the % sign or vim will expand it to the current filename.

But you might try:

:help sub-replace-expression

if you don't want to use an external filter.

Upvotes: 1

Related Questions