Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Need help with data file 1

Status
Not open for further replies.

sachrash

MIS
Jun 4, 2003
7
US
I have following data file
-----------------------------------
abc 123
abc 456
xyz 123
xyz 456
pqr 123
--and so on
----------------------------------
I am trying to get output in following format using awk.

------------------
abc 123;456
xyz 123;456
pqr 123;
------------------
Any help from al you awk Guru's is highly appreciated.

Thanks
 
If order is not important, this will do what you want.

{
if (!a1[$1]) {
a1[$1] = $0
}
else {
a1[$1] = a1[$1] ";" $2
}
}
END {
for (b in a1) print a1
}

CaKiwi

"I love mankind, it's people I can't stand" - Linus Van Pelt
 
If order is important, try this

{
for (j=1;j<=n;j++) {
if (a1[j] == $1) {
a2[j] = a2[j] &quot;;&quot; $2
next
}
}
n++
a1[n] = $1
a2[n] = $0
}
END {
for (j=1;j<=n;j++) print a2[j]
}

CaKiwi

&quot;I love mankind, it's people I can't stand&quot; - Linus Van Pelt
 
Sorry, I forgot to turn off tgml for my first post. Here it is again.

{
if (!a1[$1]) {
a1[$1] = $0
}
else {
a1[$1] = a1[$1] &quot;;&quot; $2
}
}
END {
for (b in a1) print a1

CaKiwi

&quot;I love mankind, it's people I can't stand&quot; - Linus Van Pelt
 
CaKiwi

What if the incoming file looks like below:
----------------------------------
&quot;abc&quot;,&quot;This is line1&quot;
&quot;abc&quot;,&quot;This is line2&quot;
&quot;xyz&quot;,&quot;This is line for xyz&quot;
&quot;pqr&quot;,&quot;This is line 1 for pqr&quot;
&quot;pqr&quot;,&quot;This is line 2 for pqr&quot;
-------------------------------------

Outpur should look like below:
-------------------------------------
&quot;abc&quot;,&quot;This is line1;This is line2&quot;
&quot;xyz&quot;,&quot;This is line for xyz;&quot;
&quot;pqr&quot;,&quot;This is line 1 for pqr;This is line 2 for pqr&quot;
-------------------------------------

Thanks so much in advance!
 
If you have any more questions, tell me if you want the order of the original file preserved. This assumes you do.

BEGIN {FS=&quot;,&quot;}
{
for (j=1;j<=n;j++) {
if (a1[j] == $1) {
a2[j] = a2[j] &quot;;&quot; substr($2,2,length($2)-2)
next
}
}
n++
a1[n] = $1
a2[n] = substr($0,1,length-1)
}
END {
for (j=1;j<=n;j++) print a2[j] &quot;\&quot;&quot;
}

CaKiwi

&quot;I love mankind, it's people I can't stand&quot; - Linus Van Pelt
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top