RaamEE
RaamEE

Reputation: 3517

How to search in vim for a value and then use the value to do search and replace in the same line?

I have the following set of lines, where the 1st column is a Scenario name and it's followed by a list of parameters.

I want to use the 1st column value as a value to the parameter scen=, which may be anywhere in the list of parameters.

For example, If I start with:

InstallFull server1=solaris10 server2=solaris11 scen= email= disk=
InstallPartial server1=solaris20 server2=solaris21 email= scen= disk=
InstallMinimum server1=solaris30 server2=solaris32 disk= email= scen= 

I would like to end up with this:

InstallFull server1=solaris10 server2=solaris11 scen=InstallFull email= disk=
InstallPartial server1=solaris20 server2=solaris21 email= scen=InstallPartial disk=
InstallMinimum server1=solaris30 server2=solaris32 disk= email= scen=InstallMinimum

I used the following search and replace with back-references syntax:

:%s/\(.\{-\}\) \(.*\)\(scen=\)\(.*\)/\1 \2 \3\1 \4/gc

but I am looking for an easier way.

Maybe there is a way to run multiple commands, where the 1st command saves the search result into a variable and the 2nd command uses the variable to do a search and replace.

I am looking for a VI one-liner command(s), but functions are also welcomed if such one-liners don't exist. :-)

Thanks.

RaamEE

Upvotes: 2

Views: 97

Answers (3)

Peter Owens-Finch
Peter Owens-Finch

Reputation: 11

I would make a macro that looks like this. Place the cursor on the first line, and

qq^"ayiw:s:\Vscen=:\= submatch(0) . @a

Press enter here. Then

jq

After that, just hit @q with the number of times you want to perform it. If you want to do it 10 times, 10@q

Upvotes: 1

Kent
Kent

Reputation: 195229

%s/\v^(\w+).*/\=substitute(getline('.'),'scen=','&'.submatch(1),'g')/

this line looks long but easier to understand.

P.s. this line works if your line has multiple target patterns (scen= here)

Upvotes: 1

Ingo Karkat
Ingo Karkat

Reputation: 172758

A (shorter) alternative would be :global with normal mode commands that yank the first word and then append it after the scen= match:

:global/scen=/normal! yenEp

Upvotes: 2

Related Questions