Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace text before and after pattern in one command in vim

Tags:

vim

Let's say I have the following text

bar1 = foo.get('abc1')
bar2 = foo.get('abc2')
bar3 = foo.get('abc3')

and I would like to search and replace all the occurrences of foo.get(...) with foo[...] in order to obtain:

bar1 = foo['abc1']
bar2 = foo['abc2']
bar3 = foo['abc3']

How could I do that in vim in one search/replace command?

like image 620
BiBi Avatar asked Aug 10 '26 18:08

BiBi


1 Answers

The following should work: :%s/foo.get(\(\W\+\)\(\w\+\)\(\W\+\))/foo\[\1\2\3].

Here, the main logic is to store ', abc1 and ' to \1, \2 and \3 which can later be back referenced. Similarly for other two lines.

like image 94
weirdsmiley Avatar answered Aug 13 '26 14:08

weirdsmiley



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!