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

Computer Problems? Computing.Net has over 1,000,000 posts about all things technology related! Over 90% answered within 24 hours! Click here to start participating now! Also, be sure to check out the New User Guide.

joining file lines with awk

Reply to Message Icon

Name: asic1984
Date: June 13, 2008 at 07:34:52 Pacific
OS: unix
CPU/Ram: intel
Product: 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 ?



Sponsored Link
Ads by Google

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

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


0

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

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


0

Sponsored Link
Ads by Google
Reply to Message Icon

Related Posts

See More


file existance Replace leading zeroes wi...



Post Locked

This post is quite old and has been locked from receiving new replies. Please create a new posting instead.


Go to Unix Forum Home


Sponsored links

Ads by Google


Results for: joining file lines with awk

find the number of line with awk. www.computing.net/answers/unix/find-the-number-of-line-with-awk/4554.html

joining lines with sed www.computing.net/answers/unix/joining-lines-with-sed/6674.html

calculating expressions with awk www.computing.net/answers/unix/calculating-expressions-with-awk/4834.html