2

I have written three hive queries in shell script for calculating debit-credit and target amounts which output below values:

debit_amount :  BOI 4760545.650000 AXIS 284.49000000 SBI 87.220000000 ICICI 14199.66000

credit_amount :  BOI 3424.65 AXIS 43.4546 SBI 4.54546 ICICI 3423.3465

target_amount : BOI 4757121.000000 AXIS 241.0354 SBI 82.67454 ICICI 10776.3135

now I want to calculate debit-credit amount for each bank and compare with target_amount value

How to write it in shell script?

I tried with awk command but didn't get required output.

2
  • Try using grep -Eo. Check both flags in man grep.
    – theoden8
    Commented Dec 30, 2015 at 13:52
  • What shell do you use?
    – choroba
    Commented Dec 30, 2015 at 14:22

2 Answers 2

0

Easy in Perl:

echo "$output" | perl -lane '
$amount{$F[$_]}{$F[0]} = $F[$_ + 1] for 2, 4, 6, 8
}{
for $bank (grep $_, keys %amount) {
    print $bank, "\t",
          $amount{$bank}{debit_amount} - $amount{$bank}{credit_amount} - $amount{$bank}{target_amount}    
}
' 
  • -n reads the input line by line
  • -a splits each line on whitespace to the @F array
  • -l adds a newline to print

Most shells don't support floating point arithmetics, so using an external tool is inevitable. Here is an example of bash using bc for computations:

amounts=($output)
for bank_idx in 2 4 6 8 ; do
    printf '%s\t' ${amounts[bank_idx]}
    bc -l <<< "${amounts[bank_idx + 1]} - ${amounts[bank_idx + 11]} - ${amounts[bank_idx + 21]}"
done

${amounts[@]} is an array constructed from the whole input. For each bank (indices 2, 4, 6, and 8), debit is stored at index + 1, credit at index + 11, and target at index + 21.

0

an awk solution, the awk file

/debit_amount/ { for(i=3;i<=NF;i+=2) { bank[$i]=1 ; debit[$i]=$(i+1) ; } }
/credit_amount/ { for(i=3;i<=NF;i+=2) { bank[$i]=1 ; credit[$i]=$(i+1) ; } }
/target_amount/ { for(i=3;i<=NF;i+=2) { bank[$i]=1 ; target[$i]=$(i+1) ; } }

END {
  for ( b in bank ) printf "%-10s: d %f c %f t %f (%f) : %f\n",
      b,debit[b],credit[b],credit[b]-debit[b],target[b],target[b]+credit[b]-debit[b] ;
}

to be run as

awk -f test.awk u

and give

BOI       : d 4760545.650000 c 3424.650000 t -4757121.000000 (4757121.000000) : 0.000000
AXIS      : d 284.490000 c 43.454600 t -241.035400 (241.035400) : 0.000000
ICICI     : d 14199.660000 c 3423.346500 t -10776.313500 (10776.313500) : 0.000000
SBI       : d 87.220000 c 4.545460 t -82.674540 (82.674540) : 0.000000

you can adjust printed field in printf statement.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .