3

I have a line looking like this:

pattern1 any text pattern2 any text pattern2 any text pattern2 any text

And I want it to become:

pattern1 any text
pattern1 pattern2 any text
pattern1 pattern2 any text
pattern1 pattern2 any text

and I'll be applying this to thousands of lines

This command: %s/\(pattern1\).\{-}\zs.\(pattern2\)\|\(pattern2\)/\r\1 \2 \3/g

Is only producing:

pattern1 any text
pattern1 pattern2  any text
  pattern2 any text
  pattern2 any text

Because of the \| in the search string I think.

Any pointers?

2 Answers 2

2

That answer works for plain text, but not for patterns - you can't have patterns in the replace string unless you use an evaluated expression \=.

I've figured this out:

:%s/pattern2/\="\r" . matchstr(getline('.'), 'pattern1') . submatch(0)/g

So in my actual file, I'd use

pattern1 = .\{-}:  (everything up to the first colon)
pattern2 = \d\+ \a\+: (a date in the format dd mmm:)

resulting in

:%s/\d\+ \a\+:/\="\r" . matchstr(getline('.'), '.\{-}:') . submatch(0)/g
0

Why not just replace pattern2 by \n pattern1 pattern2?

:%s/pattern2/\rpattern1 pattern2/g

or without repeating pattern2:

:%s/\(pattern2\)/\rpattern1 \1/g

Both change

pattern1 any text pattern2 any text pattern2 any text pattern2 any text

to

pattern1 any text 
pattern1 pattern2 any text 
pattern1 pattern2 any text 
pattern1 pattern2 any text

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.