Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vim Regex Duplicate Lines Grouping

I have a log file like this:

12 adsflljl
12 hgfahld
12 ash;al
13 a;jfda
13 asldfj
15 ;aljdf
16 a;dlfj
19 adads
19 adfasf
20 aaaadsf

And I would like to "group" them like one of these two:

12 adsfllj, 12 hgfahld, 12 ash;al
13 a;jfda, 13 asldfj
15 ;aljdf
16 a;dlfj
19 adads, 19 adfasf
20 aaaadsf

Or

12 adsfllj, hgfahld, ash;al
13 a;jfda, asldfj
15 ;aljdf
16 a;dlfj
19 adads, adfasf
20 aaaadsf

And I am totally stuck. And if vim doesn't do it, I have sed and awk and bash too. I just don't really want to write a bash script, I want to increase my regex-fu

like image 599
Steve Avatar asked Dec 09 '22 05:12

Steve


1 Answers

In Vim you can use:

:%s/\(\(\d\+\) .*\)\n\2/\1, \2/g 

which means: if a group of numbers is matched after a new line, remove the newline and place a comma instead. If you are not familiar with them, \1 and \2 are backreferences.

Unfortunately this only merges two occurrences at a time, so you'll have to run it multiple times before achieving your goal.

EDIT: one way to do it in a single go would be to cycle and exploit the fact that the as soon as the file doesn't match anymore an error is issued. The error is a bit annoying though, but I couldn't do better with a one-liner:

:while 1 | :%s/\(\(\d\+\) .*\)\n\2/\1, \2/g | :endwhile
like image 100
UncleZeiv Avatar answered Feb 14 '23 01:02

UncleZeiv