AWK formatting help.

Dear all

I require help with AWK regarding this situation

Input is :

fn1 12345
fn1 23456
fn3 231513
fn1 22325
fn3 123125

Desired output is

fn1 12345 23456 22325
fn3 231513 123125

Of course to be taken in mind that fn(n) can be anywhere but always $1

I have some messy shell code to achieve this, but it's not worth pasting.

Thank you for your assistance.
Best regards
Peasant.

awk '{a[$1]=a[$1]?a[$1] FS $2:$2}END {for(i in a)print i, a}' file
awk '$1 in a{a[$1]=a[$1] FS $2; next} {a[$1]=$2} END{for(e in a) print e, a[e]}' infile

Thanks folks.

Since i'm still in process of mastering AWK, some hints would be very useful (explanation of code execution)
Documentation online is ok, but it really lacks real life examples elaborated (like this).

Regards
Peasant.

$ ruby -ane 'BEGIN{h={}};(h[$F[0]]||=[])<<$F[1];END{h.each{|x,y|puts "#{x} #{y.join(" ")}"}}' file
fn1 12345 23456 22325
fn3 231513 123125

Create a hash, store first field as key and second field as value if key is found, otherwise, initialize the value an empty array. At the end, print the hash.

awk '{a[$1]=a[$1]?a[$1] FS $2:$2}END {for(i in a)print i, a}' file

Here a value is assigned to the array element a[$1] with a condition expression operator:

a[$1]=a[$1]?a[$1] FS $2:$2

Explanation:

a[$1]? -> if a[$1] has a value then 
  a[$1]=a[$1] FS $2
else 
  a[$1]=$2
1 Like