Is that possible to use awk
to values of same key into one row?
For instance
a,100
b,200
a,131
a,102
b,203
b,301
Can I convert them to a file like this:
a,100,131,102
b,200,203,301
Is that possible to use awk
to values of same key into one row?
For instance
a,100
b,200
a,131
a,102
b,203
b,301
Can I convert them to a file like this:
a,100,131,102
b,200,203,301
tl;dr
If you presort the input, it is possible to use
sed
to join the lines, e.g.:A bit more explanation
The above one-liner can be saved into a script file. See below for a commented version.
parse.sed
The logic here is as follows:
Run it like this:
Output:
If Perl is an option,
These command-line options are used:
-n
loop around each line of the input file-l
removes newlines before processing, and adds them back in afterwards-a
autosplit mode – split input lines into the@F
array. Defaults to splitting on whitespace.-e
execute the perl code-F
autosplit modifier, in this case splits on,
@F
is the array of words in each line, indexed starting with$F[0]
$F[0]
is the first element in@F
(the key)$F[1]
is the second element in@F
(the value)%a
is a hash which stores a string containing all matches of each keyYou can use awk like this:
We use
-F,
to use comma as delimiter and use arraya
to keep aggregated value.Reference: Effective AWK Programming
With datamash
From manual: