Computing.Net > Forums > Unix > Awk - split lines into arrays after getline

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.

Awk - split lines into arrays after getline

Reply to Message Icon

Name: peternguyen
Date: September 3, 2009 at 07:27:53 Pacific
OS: Windows XP
Subcategory: General
Tags: awk, getline, split, array
Comment:

Hi, i'm trying to compare two files. The content of the files are organized in the same way, first field is the name of the item, second field is the price. Eg.

oldpricelist.txt

apples,2
bananas,3
grapes,1

newpricelist.txt

apples,2
bananas,4
grapes,1
melon,5

What i'm trying to do is, go through "newpricelist" line by line, firstly checking to see if it exists in the "oldpricelist", if it doesn't ignore, but if it does exist, then check if the price is the same, then print a message if the prices does or doesn't match.

So far, i have written an awk script to get me as far as finding what exists in the "oldpricelist" but once i get to this point, i don't know how to proceed to comparing the PRICE, because i can't figure out how to use arrays in awk properly.

Here's what i have:

awk -F, 'BEGIN {
while ((getline < "oldpricelist.txt") > 0)
array[$1] = $1
OFS=","}
{if (array[$1])
#if a match of fruit is found, proceed to compare price
if(???)
print "price match"
else
print "new price"
}' newpricelist.txt

Any help is much appreciated. Thanks.



Sponsored Link
Ads by Google

Response Number 1
Name: nails
Date: September 3, 2009 at 21:18:27 Pacific
Reply:

Since my OS is Solaris, I am using nawk. Let me know if you have any questions:

nawk  ' BEGIN { FS=",";
  while ((getline < "oldpricelist.txt") > 0)
     myarray[$1] = $2
}
{

if($1 in myarray)
   if(myarray[$1] == $2)
      printf("%s: price match\n", $1)
   else
      printf("%s: new price \n", $1)

}' newpricelist.txt


1

Response Number 2
Name: peternguyen
Date: September 4, 2009 at 00:36:20 Pacific
Reply:

Thanks! Works nicely.


0

Sponsored Link
Ads by Google
Reply to Message Icon

Related Posts

See More


sed: conditional newline ... csv processing using shel...


Use following form to reply to current message:

Login or Register to Reply
LoginRegister


Sponsored links

Ads by Google


Results for: Awk - split lines into arrays after getline

Split row into meaningful records www.computing.net/answers/unix/split-row-into-meaningful-records/7783.html

Join 2 lines into 1 www.computing.net/answers/unix/join-2-lines-into-1/7680.html

Unix n(awk) system() command www.computing.net/answers/unix/unix-nawk-system-command/6760.html