0

I want to perform a search and replace. A newline before any non-digit should be replaced with tab. I tried

%s/\n\D/\t/g

but it replaced the first character of the word following the newline, which is not what I wanted, i.e.

abcd
abcd

to

abcd   bcd

I want to preserve a after the newline.

3

You're almost there, but your regular expression is replacing both the newline and the non-digit with a tab.

How about replacing every newline followed by a non-digit with a tab and that same non-digit?

%s/\n\(\D\)/\t\1/g

The escaping is a bit messy, but basically you have a grouping around the \D that will capture whatever the non-digit is. This is then referred to with \1 to insert it after the tab.

  • If you have further groups in your search pattern, these are accessible through \2, \3 etc. This is not limited to s/.../.../ in Vim but usually works like this in most tool using s/.../.../ (most notably sed). – Kusalananda Jun 24 '16 at 8:53
  • 2
    use the very magic option \v to deal with too many escapes %s/\v\n(\D)/\t\1/g – Sundeep Jun 24 '16 at 8:53
  • @spasic That's a Vim thing, right. Or where is it documented elsewhere? Actually, in this case, it doesn't make it look much prettier as you only get rid of one backslash... ;-) – Kusalananda Jun 24 '16 at 9:03
  • 1
    yeah, it is specific to Vim and it makes it easier to use regex elements like ( ) | {} free of escaping.. the \V is opposite.. see :h \v for more info – Sundeep Jun 24 '16 at 9:41
1

One way to do it is to use the end match marker:

%s/\n\ze\D/\t/

Another way to do it is to using negative lookahead:

%s/\n\d\@!/\t/

They are not exactly equivalent, the second will also replace the last newline in a file.

  • Thanks Sato, both worked, but @Kusalananda replied first.... – Rohail Abbas Jun 24 '16 at 9:02
-2

I hope this will help you

:%s#\n.\D#\t#g
  • 1
    This has the feature that it gobbles up two characters, and it also matches digits directly after newlines, which was not wanted. Please test your answers. – Kusalananda Jun 24 '16 at 6:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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