Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

vim search and replace a variable string

Tags:

regex

replace

vim

I have a paatern like this.

func(a, "a");
func(b, "b");
func(abc, "abc");
...

I wish to replace them with

func(a);
func(b);
func(abc);
...

In vim, how can i do it?

like image 943
Sandeep Avatar asked Jun 27 '26 06:06

Sandeep


2 Answers

This should do it.

:%s/func(\([^,]*\),\s*"\1"/func(\1/g
like image 175
R Sahu Avatar answered Jun 29 '26 20:06

R Sahu


If, like me, you were trying to figure out how to search and replace while leaving some substring in place, you do it with capture groups

R Sahu's solution uses capture groups, but since I didn't know what they were called I couldn't look it up.

Here's another example of capture groups:

public User updateUser(String username, Optional<String> newUsername, Optional<String> newPassword, Optional<String[]> newRoles) {
// :s/\vOptional\<([a-zA-Z\[\]]*)\>/\1/g
public User updateUser(String username, String newUsername, String newPassword, String[] newRoles) 

Search Definition

:s search only one line

Search String

\v assume any characters other than letters, numbers and underscores are special characters ("very magic" mode)

Optional\< match the literal phrase 'Optional<'

([a-zA-Z\[\]]*) capture a combination of letters and [ ]s to be used later

\> match the literal phrase '>'

Replace String

\1 insert the first captured group

Global Flag

g replace every found instance, not just the first one

like image 33
jeffrey.d.m Avatar answered Jun 29 '26 20:06

jeffrey.d.m



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!