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

Concatenate records based on first column in each record

Status
Not open for further replies.

Haazi2

Programmer
Aug 25, 2000
51
US
I have a file with records such as:

111112 4000000001 01/01/13 13:05
111112 4000000002 02/02/13 13:05
111112 4000000003 03/03/13 13:05
111113 4000000004 04/01/13 07:05
111113 4000000005 05/01/13 10:05
111113 4000000006 06/01/13 17:05
111114 4000000007 06/01/13 18:05
111114 4000000008 06/01/13 19:05
111114 4000000009 06/01/13 20:05

1st column is an customer id, 2nd column is an acct. no.

I would like it in this format:

111112,4000000001,4000000002,4000000003
111113,4000000005,4000000005,4000000006
111114,4000000007,4000000008,4000000009

I have this script:

BEGIN { RS = "\n"; FS = " "}
{
prev = ""
oneof = ""
print "mrn: ", $1
print "acct: ", $2
print "admit date: ", $3
print "admit time: ", $4
print ""

$1!=prev
{
prev = $1
oneof = ""
}

if ( $1 && $1 == prev )
{
oneof=oneof$1","$2","
print "oneof: ", oneof
next
}
}
I get the following output:
111112,4000000001, and so on

I'm messing up on my logic. prev is supposed to keep track of the current customer id as mrn changes. As long as prev equals mrn you concatenate all the accounts. When the customer id changes, change prev to the new mrn then start concatenation again. Maybe someone can point me in the right direction to get the correct format.


 
A starting point:
Code:
awk 'NR==1{printf "%s",$1;prev=$1}$1==prev{printf ",%s",$2;next}{printf "\n%s,%s",$1,$2;prev=$1}END{printf "\n"}' /path/to/input

Hope This Helps, PH.
FAQ219-2884
FAQ181-2886
 
Thanks PHV. This helped a lot. I added on some things because I made some changes. I'm new to awk but I use perl, ksh, and sed so it's just some awk concepts I need to learn then the syntax. AWK seems to be a very useful tool to add to the arsenal. I plan use it more often in the future.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top