Nick.h
Nick.h

Reputation: 4255

How can I do this search&replace with vim?

I have a text file containing these lines:

options[15]=new Option("text1","25");

options[16]=new Option("text2","23");

options[17]=new Option("text3","12");

(and more...)

How can I replace each line with text# ?.for example first line should be replaced by text1, second line with text2,etc...

Upvotes: 0

Views: 108

Answers (4)

Alan Gómez
Alan Gómez

Reputation: 378

This regex should work also:

:%s/^.\{-}\(".\{-}"\).*/\1

The part ^.\{-} match everything till the group \(".\{-}"\), what is the target text to keep, finally \1 do the replacement.

Upvotes: 0

Peter Rincker
Peter Rincker

Reputation: 45177

As an alternative to :s and using a macro, I sometimes find :normal to be very pleasant.

%norm df"f"d$

We can short this up but using ; motion which will repeat the f" motion and use D which is the same as d$

%norm df";D

Upvotes: 3

user908230
user908230

Reputation: 21

It looks like you already have them in the source. Assuming that you have the lines like this:

options[15]=new Option("text#","25");
...

And you want to change to this:

options[15]=new Option("text15","25");
...

Here is what you do: change the first line to text1 yank "text1"

create a macro (qq)
/text
dw
p
ctrl+a
b
vwly
q

Then if you have 25 lines: do 23@q

23 invocations of the macro since you have done the first two manually.

Upvotes: 2

ZyX
ZyX

Reputation: 53674

Read :h /\(

%s/\Voptions[\d\+]=new Option("\(text\d\+\)","\d\+");/\1/g

Upvotes: 2

Related Questions