Hongxu Chen
Hongxu Chen

Reputation: 5350

Is is possible to substitute the matched pattern in vim?

Every time before I replace pattern1 with pattern2, I usually use /pattern1 to confirm the regex is the right one. When doing the actual substitution, however, I have to use :%s/pattern1/pattern2/g(Suppose I need to do the global replacement). This is annoying and may fail due to typos.

So is there a convenient way to substitute the matched pattern1?

Upvotes: 0

Views: 151

Answers (5)

Kent
Kent

Reputation: 195029

// is last search :%s//replacement/g will do what you want.

however you could also think about %s/pattern1/pattern2/gc or %s/p1/p2/gn

Upvotes: 4

Gabi Purcaru
Gabi Purcaru

Reputation: 31524

You can use something like :%s/pattern/replace/c (notice the trailing c) and vim will ask for confirmation.

Upvotes: 1

Ingo
Ingo

Reputation: 36329

I think that:

:.,.+3s//repl/g

should replace every occurence of the current pattern in the next 3 lines with repl.

Upvotes: 1

romainl
romainl

Reputation: 196466

Just use an empty pattern:

:%s//pattern2/g

Upvotes: 1

D Mac
D Mac

Reputation: 3809

The null string in the first half of the s command defaults to the last searched pattern.

So

g/fred/s//mary/g

changes all instances of fred to mary.

Upvotes: 1

Related Questions