Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vim Substitution

I always wanted to know, how you can substitute within given parameters.

If you have a line like this:

123,Hello,World,(I am, here), unknown

and you wnat to replace World with Foobar then this is an easy task: :%s/World/Foobar/

Now I wonder how I can get rid of a , which is wihtin the ( ).

Theoretically I just have to find the first occurance of ( then substitute the , with a blank until ).

like image 321
Ajin Avatar asked Mar 07 '12 15:03

Ajin


1 Answers

Try lookahead and lookbehind assertions:

%s/([^)]*\zs,\ze.*)//

(\zs and \ze tell where pattern starts and end)

or

%s/\(([^)]*\)\@<=,\(.*)\)\@=//

The first one is more readable, the second one uses \( ... \) groupings with parentheses inside groups which makes it look like obfuscated, and \@<= which apart from being a nice ASCII-art duck is the lookbehind operator, and \@= that is the lookahead operator.

References: :help pattern (more detail at :help /\@=, :help /\ze, etc.)

You use the GUI and want to try those commands? Copy them into the clipboard and run :@+ inside Gvim.

like image 191
Benoit Avatar answered Oct 09 '22 19:10

Benoit