Tom's Guide | Tom's Hardware | Tom's Games
![]() |
![]() |
![]() |
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 ?

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]";"}}
' fileinThis 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

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;11thanks too much for yout help

![]() |
file existance
|
Replace leading zeroes wi...
|

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