vim how to combine lines containing same id

Viewed 63

I have a csv file and I want to combine lines with same id. Example:

ID,Name
1113,Firefox
1114,Chrome
1113,InternetExplorer

and it should look like:

ID,Name
1113,"Firefox,InternetExplorer"
1114,Chrome

Thanks

2 Answers

Awk might be a solution for you, something like this might be sufficient:

:2,$!awk -F, '{ a[$1] = (a[$1] ? a[$1] "," : "") $2 } END { for (p in a) print p "," a[p] }'

It would join lines on their first column and concatenate all the second columns with a comma:

ID,Name
1113,Firefox,InternetExplorer
1114,Chrome

The second column isn't quoted when outputted, nor is the sorting guaranteed.

For VIM approach,

  1. Sort from the second line to end of file.
:2,$sort
  1. Create Marco 'a' starting from second line beginning
qa              ---> Record Macro 'a' 
vw"1y           ---> Copy column 1 value including "," to register '1'
V               ---> Select whole line
G?<CR>1<Enter>  ---> Go to end of file then search backward for last occurrence of 
                     register '1' to select all lines with same column 1 value
:'<,'>join      ---> Join selected lines 
:.s/ <CR>1/,/ge ---> Replace register '1' with a space in front to "," 
0wa             ---> Go to begin of line and move to the "," then append
"               ---> Append "
<ESC>$a         ---> Back to command mode and go to end of line then append 
"               ---> Append "
<ESC>j0         ---> Back to command mode and move 1 line down and go to start of line
1               ---> Complete Marco

Then play Macro 'a' any number of time like

1000@a          ---> execute 1000 times

Constraint:
Will not work when column 2 contains value of {column 1},

Related