unix awk/sed program

i need a sample unix awk/sed program to replace param3 in a file.

i have sample file a.dat with the following format/length (week 8, sku 20, store 20 and qty 8). all store id's which end with _2 needs to be replaced with div id 2. all store id's which end with _1 needs to be replaced with div id 1.

W23_2009275 999_2 8.991052
W24_2009275 999_2 8.991052
W25_2009275 97_2 8.991052
W26_2009275 96_2 8.991052
W51_2008102 99_1 2.851916
W52_2008102 96_1 2.851916
W51_2008104 96_1 5.468747
W52_2008104 999_1 5.468747

new file b.dat should look like this

W23_2009275 2 8.991052
W24_2009275 2 8.991052
W25_2009275 2 8.991052
W26_2009275 2 8.991052
W51_2008102 1 2.851916
W52_2008102 1 2.851916
W51_2008104 1 5.468747
W52_2008104 1 5.468747

Your terminology is weird (what's a sku? what's a div? nah, never mind) but hope this helps.

awk '{ if ($2 ~ /_1$/) { $2 = 1; } else if ($2 ~ /_2$/) { $2 = 2 } print }' 

The following awk syntax works, but i need this script to be modified to also sum field4 values by distinct field1, field2, field3

awk '{print substr($0,1,27),substr($2,index($2,"_")+1)," ",substr($0,49)}' testfile.dat > testfile2.dat

Current file
W2_2009 275 999_2 8
W2_2009 275 99_2 7
W25_2009 275 97_1 5
W25_2009 275 96_1 4

New file
W2_2009 275 2 15
W25_2009 275 1 9

i need help with the following awk program needs to be modified to enforce fixed length of 8 char for the sum[i].

awk '{sum[substr($0,1,27),$2] += $3} END {for (i in sum) {print i," ",sum[i]}}' testfile2.dat> testfile3.dat

For fixed-length output, have a look at the printf function.

The "sum by distinct" can be solved by using an associative array. This is pretty much a schoolbook example of what you need it for.