How to get sub_total


 
Thread Tools Search this Thread
Top Forums Shell Programming and Scripting How to get sub_total
# 1  
Old 11-16-2010
How to get sub_total

Hi, Unix Gurus
I have a requriement as following;
source file
Code:
ID, MONTHS,                  TOTAL_AMT
1   01,02,03                     9000
2   01,02,03,04                 8000
3   03,04,05,06,07,08,09    14000

The months column may cantains 12 months

expected target
Code:
ID BUDGET_MON  BUDGET_AMT
1      01             3000
1      02             3000
1      03             3000
2      01             2000
2      02             2000
2      03             2000
2      04             2000
3      03             2000
3      04             2000
3      05             2000
3      06             2000
3      07             2000
3      08             2000
3      09             2000

Basically, I need print out every single month and monthly budget which is total_amt divided by number of months in second column.

Thanks in advance

Last edited by Franklin52; 11-16-2010 at 01:20 PM.. Reason: Please use code tags
ken002
# 2  
Old 11-16-2010
Homework??
# 3  
Old 11-16-2010
Try this out... input.txt file should have your input values.

FYI: this can be done little easier in awk too. but for understanding unix script will be better I think.

Code:
 
while read line
do
        ID=`echo $line | awk '{print $1}'`
        Months=`echo $line | awk '{print $2}'`
        NoOfMonths=`echo $Months | tr -dc "," | wc -c | awk '{print $1}'`
        TotAmt=`echo $line | awk '{print $3}'`
        (( BugAmt = TotAmt / ( NoOfMonths + 1 ) ))
        for Month in `echo $Months | tr ',' ' '`
        do
                echo "$ID $Month $BugAmt"
        done
done < input.txt

[Output]
1 01 3000
1 02 3000
1 03 3000
2 01 2000
2 02 2000
2 03 2000
2 04 2000
3 03 2000
3 04 2000
3 05 2000
3 06 2000
3 07 2000
3 08 2000
3 09 2000
[/output]
This User Gave Thanks to palsevlohit_123 For This Post:
# 4  
Old 11-16-2010
Using awk:

Code:
awk -F"[, ]" ' 
/ID,/ { print "ID BUDGET_MON BUDGET_AMT" }
!/ID,/ {
   for(i=2;i<NF;i++) print $1, $i,$NF/(NF-2);
}' budget.txt

Using bash/ksh
Code:
echo "ID BUDGET_MON BUDGET_AMT"
while read ID MONTHS VAL
do
   read -a M_ARRAY <<EOF
   $( IFS=","; echo $MONTHS )
EOF
   [ "$ID" = "ID," ] && continue
   for MTH in ${M_ARRAY[@]}
   do
       echo $ID $MTH $((VAL/${#M_ARRAY[@]}))
   done
done < budget.txt

This User Gave Thanks to Chubler_XL For This Post:
# 5  
Old 11-16-2010
Thanks everybody for your rapidlly reply.


Best Regards,
ken002
# 6  
Old 11-16-2010
Code:
while(<DATA>){
  next if $.==1;
  chomp;
  my @tmp = split;
  my @ids=split(",",$tmp[1]);
  foreach(@ids){
   print $tmp[0],"      ",$_,"  ",$tmp[2]/($#ids+1),"\n";
  }
}
__DATA__

This User Gave Thanks to summer_cherry For This Post:
Login or Register to Ask a Question

Previous Thread | Next Thread
Login or Register to Ask a Question