bein
bein

Reputation: 39

Shell grouping file repetitive pattern

Let say I have one file

a,anything,keyboard
b,anything,mouse
c,anything,door
a,anything,monitor
d,anything,keyboard

As result I want

a,anything,keyboard - monitor
b,anything,mouse
c,anything,door
d,anything,keyboard

Pattern "a" repeats and I want to merge "keyboard" and "monitor" as in the result.

My question is how to merge pattern that repeats in the beginning of each line (in this example, "a") into one line adding whats is different (in this example, adding the word "monitor"

cat file.csv | cut -d',' -f1 | sort -u result:

a
b
c
d

I want the result:

a,anything,keyboard - monitor
b,anything,mouse
c,anything,door
d,anything,keyboard

Upvotes: 0

Views: 53

Answers (1)

RomanPerekhrest
RomanPerekhrest

Reputation: 92874

I would call it grouping not sorting.

gawk (GNU awk) solution:

awk -F, 'BEGIN{ PROCINFO["sorted_in"]="@val_str_asc" }{ a[$1]=($1 in a)? a[$1]" - "$3 : $0 }
         END{ asort(a); for(i in a) print a[i] }' file

The output:

a,anything,keyboard - monitor
b,anything,mouse
c,anything,door
d,anything,keyboard

Upvotes: 1

Related Questions