thorondor1990
thorondor1990

Reputation: 81

vim global command matching multiple lines and merging them

I have a file which looks like this:

acc abcd etc. etc.
// line 1
// line 2
acc more words
// 3-4 more lines
acc some other words

There are some lines starting with acc and some that doesn't. I want to merge lines not starting with acc with those starting with it and still be separated by @@, so that my file has only lines starting with acc after the operation:

acc abcd etc. etc.@@//line 1@@//line 2
acc more words@@//3-4 more lines
acc some other words

I tried below command using global to segregate each set of lines and replace \n with @@:

:%g/^acc.*\_.\{-}\(^acc\)\@=/s/\n/@@/g

But I'm able to get only the first \n replaced by @@ inside each pattern match of :g.

What am I doing wrong in this command? Is there an easier way to do this? Thanks.

Upvotes: 1

Views: 794

Answers (1)

romainl
romainl

Reputation: 196476

I would rather do it in several simple and intuitive steps than do it in a single complicated and hard-to-reason-about step. It seems like a more efficient approach to that kind of problem.

For example:

:v/^acc/s/^/@@
:%s/\n^@@/@@/

Explanation:

  • prepend each line not starting with acc with @@,
  • substitute every newline followed by @@ with @@, effectively joining all the @@ lines together and with the acc lines.

Upvotes: 2

Related Questions