Hello guys, I just start trying out AWK and encounter a problem, I try to think a bit but seems my way is incorrect.
I have two input file, with the first file has only one field, the second file has 3 fields, I suppose to do stuffs to them by writing an awk program, kinda sort them out. Since I am not suppose to know how many records the first file has, I cant just use a for loop. I would like to save each record of the first file into an array so I can begin to compare to second file and sort thing out. But I am not sure how, can you guys give me an idea?
Sorry for my english, I am not native to the language.
I did a silly attemp by doing:
{ while (NR == FNR)}
but it obvious give me an infinite loop, what I want to know is how can I tell that I can stop assign fields to array when it begins to read the second file?
So what I desire is:
File1
CoCo
Hiel
Euda
SJHF
Euda
CoCo
File2:
CoCo $39.4 paid
CoCo $34 due
Euda 45 paid
If there is no $, that line is invalid, also the two digits after decimal points.
first field can appear several times.
If first field in file 1 not appear in file 2, print out balance 0, same thing with invalid line.
Desired output:
awk '{sub(/\$/,"",$2)}/paid/{a[$1]+=$2}/due/{a[$1]-=$2}
END{for (i in a) printf "%s balance:$%.2f \n",i,a}' infile
CoCo balance:$5.40
Euda balance:$45.00
Almost giving me the right output, sorry for confusion, in file one, there is no repeating for the field, so it appear only one. Only in file 2 that it can repeat. And the calculation I think is a bit off since line without $ and without 2 numbers after decimal points are treated as invalid, so nothing should be done. Here what I test with the code:
File1:
CoCo
Hiel
Euda
SJHF
File 2:
CoCo $39.40 paid
CoCo $34.00 due
Euda 45 due
CoCo $16.05 due
Hiel $50 paid
Euda $12.45 due
Out put:
CoCo balance:$-10.65
Euda balance:$-57.45
Hiel balance:$50.00
Thank you sir. Oh, how I flip the code so file 1 will go before file 2? The order how it goes is pretty important for me. Also, how do I make exception when the amount column doesnt have dollars sign, or 2 digits after decimal points to be ignored? That would make Euda to have $-12.45, not $-57.45
It is a requirement :\
Oh, I also manage to make any line that contain no decimal points or has less than two or more than two digits after decimal points fail.
Yes, awk is a well thought out, compact, yet powerful language; although a script this long should usually not really be written on one line, this would normally be easier to read: