Tom's Guide | Tom's Hardware | Tom's Games
![]() |
![]() |
![]() |
can someone help me. i want to combine two files together in awk (i have sh).
Example:
File1.txt
12345 10
12342
53221 3File2.txt
53221 6
12345 8
12342 5
57852 10basically the program matches the first numbers, and adds the second ones together. so output is displayed as:
53221 9
12345 18
12342 5
57852 10order doesnt matter. also, one of the files should be opened in the program. so command to run it would be:
awk -f program.awk file1.txt
please help. thank youuuuuu

This looks like homework, but I'll do the hard part and help you get started:
With awk, solving this type of problem reading one of the files into an associative array. This happens in the BEGIN section.
In the main processing section as the second file is read, simply update the array with field 1, $1, and field 2, $2.
When the processing completes, print out the array in the END section. The syntax for printing an awk array is:
for (i in n)
.....Here is the script:
#!/bin/sh nawk ' BEGIN { while ( getline < "file1.txt" > 0 ) { if(NF == $2) $2=0 n[$1]=$2 } } { # do your processing here } # END processing goes here ' file2.txt # end scriptIf you want to learn how to how to place awk scripts in external files:
awk -f myscript.awk myfile.in
check out this link:
http://www.ibm.com/developerworks/l...
search for 'External scripts'

thanks for the help. i'm just confused as what this does
if(NF == $2) $2=0
when number of fields is equal to the value of the second field, set second field to zero??
i modified it to say if the second field is empty, set it to 0if(NF == 1 || NF > 2) $2=0
also, i open the second file from external, but how do i set the values in an array just like the first file? i tried saying
a[$1] = $2
in the processing section, but that just doesnt work. i tried putting it in a loop, but that didnt work either. please help. thanks.p.s. that link is very helpful. read through it and made me understand a bit more. so thanks for that as well

oooooo i got that part :D
so now i'm reading the file and doing the necessary calculations, then printing out. the only problem that i have is that if i have $1 in file2 that i dont have in file1, i cant output that. i mean...for(i in n)
{
if($1 != i) n[$1] = $2
}i cant do that cause it rewrites it most of the time. i just want to add those from file2 that are not in file1 to the array 'n'
thanks

You do not want to replace; you want to add.
In the main processing loop, you do this:
n[$1]+=$2
which is another way of saying:
n[$1]=n[$1]+$2

oh wow, i was actually using a loop in there, and having an if statement saying
for(i in n)
{
if(n[$1] == i) n[]+ = $2
}
i guess we dont even need that loop, which actually solves my problem. wow, awk is impressive.thank you very much for your help :)

![]() |
![]() |
![]() |
| Login or Register to Reply | |
| Login | Register |
| Ads by Google |