Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Positive look-behind assertion and substitution with Vim?

Tags:

regex

vim

I would like to use Vim to match a regular expression and perform a substitution. I have a tsv file with lines that look like this:

rs11223-A        -A
rs23300-G        -TTA
rs9733-T          -G
rs11900000-GT    -TTG

I wish to substitute the dash (-) character for a tab only in the first column after the rs...

In Vim I was attempting to perform the substitution using:

:%s/(?<=^rs[0-9]{1,12})-/\t/g   

Could anyone point out what my problem is and a correct solution?

like image 767
drbunsen Avatar asked Nov 17 '11 15:11

drbunsen


2 Answers

It may be dependent on configuration, but in my environment I have to prepend { , } with \.

Also, Vim has \zs and \ze to start and end matching, so you usually don't have to deal with normal regex lookaround.

This does what you want:

:%s/^rs\d\{1,12}\zs-/\t/g
like image 87
Jay Avatar answered Nov 16 '22 03:11

Jay


Positive look behind is done using:

\@<=

So you could use something like:

:%s/\d\@<=-/\t/g

Your actual data may be more complex, but with what you posted you could also just settle for:

:%s/-/\t

If rs should be at the beginning of the line, you can use \zs to specify the start of the match and use anchoring (^):

:%s/^rs\d*\zs-/\t
like image 30
heijp06 Avatar answered Nov 16 '22 02:11

heijp06