the pickle
the pickle

Reputation: 678

vim regex that combines all items

I have a file in the following format

1 2472
1 664
2 2600
10 4135
10 5606
...

and I want to convert it to

1 2472 664
2 2600
10 4135 5606
...

Upvotes: 0

Views: 112

Answers (3)

Alan Gómez
Alan Gómez

Reputation: 378

A reliable complete regex-based solution is also possible.

First, you must highlight non-repeated indices as follow:

:%s/\(^\(\d\).\)\(\(.\|\(\n\)\1\)\+$\)/*\1\3/

Next, must do the collapse of lines with:

:%s/\n\(*.*$\)\@!\d\+ / /

And lastly, remove * exceed character

:%s/^*//g

Best regards!

Upvotes: 0

You can combine items by executing this command:

:%s/\v(\d+\s)(.*\n\1.*)+/\=substitute(submatch(0),'\n'.submatch(1),' ','g')/

Upvotes: 6

Faibbus
Faibbus

Reputation: 1133

With multiline support, you can go with:

^(\d+) (\d+)$[.\s]+?^\1 (\d+)

See it on regex101.

The idea is to use backreferences to match two lines.

In vim's syntax, you'd write it as follows:

:%s/\_^\(\d*\) \(\d*\)\_$\_.*\_^\1 \(\d*\)/\1 \2 \3/

Upvotes: 0

Related Questions