Computing.Net > Forums > Unix > joining file lines with awk

joining file lines with awk

Reply to Message Icon

Original Message
Name: asic1984
Date: June 13, 2008 at 07:34:52 Pacific
Subject: joining file lines with awk
OS: unix
CPU/Ram: intel
Model/Manufacturer: intel
Comment:

hi

i have a file that contains data like this sample :

22;ytr;
22;fd;
22;jj;
33;ht;
33;oo;
44;tt;

i need to join lines that start with the same number to be like this

22;ytr;fd;jj;
33;ht;oo;
44;tt;

how can i achieve that using awk ?


Report Offensive Message For Removal


Response Number 1
Name: James Boothe
Date: June 13, 2008 at 12:29:35 Pacific
Reply: (edit)

Here are two completely different approaches.

The first solution assumes that each line will have, in addition to the key field, only one value.  Additional fields would simply be ignored.  Also, this first solution declares the semicolon as the field separator.  And since they are delimiters and not part of the column values, this solution has to explicitly put them back into the output.  Additional code could be added to process multiple columns.

awk -F\; '\
{a[$1]=a[$1] ";" $2}
END {for (i in a){print i a[i]";"}}
' filein

This second solution is not word oriented, thus it does not care what the field separator is set to.  Instead, it isolates the key field as being through the first semicolon, and all remaining data on the line is grabbed, regardless of how many columns.

awk '\
{colon=index($0,";")
key=substr($0,1,colon)
 a[key]=a[key] substr($0,colon+1)}
END {
for (i in a)
   print i a[i]
}' filein


Report Offensive Follow Up For Removal

Response Number 2
Name: asic1984
Date: June 13, 2008 at 21:44:23 Pacific
Reply: (edit)

hi

thanks too much for your help , it is working very good

but i donnot know why the order of the output is not the same of the input

for example if input keys are in order 11;22;33
the output order may change for example for 22;33;11

thanks too much for yout help


Report Offensive Follow Up For Removal







Use following form to reply to current message:

   Name: From My Computing.Net Settings
 E-Mail: From My Computing.Net Settings

Subject: joining file lines with awk

Comments:

 


  Homepage URL (*): 
Homepage Title (*): 
         Image URL: 
 
Data Recovery Software




Have you ever used OpenOffice?

Yes, as my main suite.
Yes, occationally.
Yes, but only once.
No, never.


View Results

Poll Finishes In 4 Days.
Discuss in The Lounge