Question

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?

Was it helpful?

Solution

This should do it.

:%s/func(\([^,]*\),\s*"\1"/func(\1/g

OTHER TIPS

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

This might work but can't say for sure until we can see more of the input:

%s/\v(.*), .*(\);)/\1\2/

Try this subsitution:

:%s/, ".\{-}"//

Explanation:

% - Run on whole file

, " - Matches the comma to first quote literally

.\{-}" - Match zero or more characters, as few as possible till "

// - Replace the matched pattern with nothing.

If you're wanting a mass edit of the lines, it can be done using regex. Follow these steps:

  1. Place cursor at top line.
  2. Shift-V to start a line visual selection.
  3. Move cursor to bottom line to select all lines you want to modify.
  4. Type ":" and you'll see ":'<,'>" appear at the bottom.
  5. Type "s/, ".*");/);/" and hit enter. The lines will change.

On #5, it's a regex search and replace. "s" denotes the operation, then the match pattern, then what to replace it with. All delimited by a / key in between them and one at the end.

If you want more info, you can find some here: http://vimregex.com/

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top