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 MikeeOK on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Print field on 1 line based on unique key

Status
Not open for further replies.

Zahier

MIS
Oct 3, 2002
97
ZA
Hi Awksters,

I am trying to write a one-liner to put fields of the same key on the same line:

Input file:
A X
A Z
B X
B Y
B Z
C X
C Y

Output file:
A X,Z
B X,Y,Z
C X,Y

I tried the code below but it doesn't work.

while read LINE
do
(( N += 1 )) && (( ! ( N % 3 ) )) && print "$LINE"
done < input.dat

Any suggestions.
 
Something like this ?
awk '
{a[$1]=a[$1]","$2}
END{for(x in a)print x,substr(a[x],2)}
' /path/to/inputfile

Hope This Help, PH.
Want to get great answers to your Tek-Tips questions? Have a look at FAQ219-2884 or FAQ222-2244
 
Thanks PHV, it helped! I then also wanted to display data in another format:
Input:

A 1 X
A 1 Y
A 1 Z
B 1 X
B 2 Y
B 2 Z
C 1 X
C 1 Y
C 2 Z

output:

A 1 X
Y
Z
B 1 X
B 2 Y
Z
C 1 X
Y
C 2 Z

I modified your code a bit to change the Field Seperator to a comma.. :)

cat input.txt | awk '{print $1,$2,",",$3}' |
awk '{FS=","}
{a[$1]=a[$1] "\n\t"$2}
END{for(x in a)print x,substr(a[x],2)}
'
It works but it does not display the output in the same order.
 
This is not tested and assumes the data is ordered appropiately.

awk '$1==sv1 && $2==sv2{print " " $3;next} {print;sv1=$1;sv2=$2}' input.txt



CaKiwi
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top