12

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?

4 Answers 4

21

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
8

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
3
  • #2 would have to be :%s/^rs\d\@<=-/\t/g
    – KomodoDave
    Aug 27, 2012 at 17:26
  • @KomodoDave: Your pattern would match rs at the beginning of the line, immediately followed by a dash (-) preceded by a single digit (positive look behind \d\@<=-). None of the lines in the data given matches that pattern. If you insist on anchoring you could use the pattern I just added.
    – heijp06
    Aug 28, 2012 at 6:50
  • I thought OP meant column in the sense of character columns, but maybe he doesn't. I copied yours to edit it and didn't replace \d with - as I intended - what I wanted to write is: :%s/^rs-\@<=/\t/g which matches '-' in the first char column after 'rs' at line start.
    – KomodoDave
    Aug 28, 2012 at 7:04
0

You want the following:

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

Vim regular expressions require some special escape sequences for {, }, ( and ).

Also, in the substitution section, you need \1 to insert your matched string.

0

The correct expression to use lookbehind is:

%s/\(\d\+\)\@<=-/\t/gc 

\(\d\+\)\@<= means to look behind positively to find digits (\d\+ means to find at least one digits). According to here, we have to capture \d\+ before applying the positive look behind, hence the \(\) around \d\+.

Also, to use the normal regex + quantifier, we have to escape it in vim (\+), see doc here.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.