Nevin Thomas
Nevin Thomas

Reputation: 826

Output filtering in shell scripting

in my script file

for file in *.TXT
do
    echo "put $file"
    less $file | grep BPR | awk -F'CACH' {'print $1'}
done

i am running this command less XYZ.TXT | grep BPR | awk -F'CACH' {'print $1'}, and i get out put like this.

BPRC000000000008801
BPRC000000000006671
BPRP000000000005088
BPRC000000000004542
BPRP000000000003805
BPRC000000000013624
BPRC000000000235668

From these out put i need to calculate amount from each line and total amount as out put.

for example

BPRC000000000008801         88.01
BPRC000000000006671         66.71
BPRP000000000005088         50.88
BPRC000000000004542         45.42
BPRP000000000003805         38.05
BPRC000000000013624         136.24
BPRC000000000235668         2356.68

and final out put should be the total amount. How can i do this. please help me.

Upvotes: 0

Views: 385

Answers (3)

devnull
devnull

Reputation: 123458

Instead of

awk -F'CACH' {'print $1'}

say

awk -F'CACH' '{c=$1;sub(/[^0-9]*/,"",c);}{print $1, c/100}'

EDIT: In order to get the total, say

awk -F'CACH' '{c=$1;sub(/[^0-9]*/,"",c);total+=c/100}{print $1, c/100}END{printf "%.2f", total}'

Upvotes: 1

jkshah
jkshah

Reputation: 11703

Try following:

awk -F'[A-Z]+' '{total += $2/100} END {printf "%.2f", total}' data

Input data:

BPRC000000000008801
BPRC000000000006671
BPRP000000000005088
BPRC000000000004542
BPRP000000000003805
BPRC000000000013624
BPRC000000000235668

Output:

2781.99

If you want output at every step:

awk -F'[A-Z]+' '{printf "%s\t%.2f\n",$0, $2/100; total += $2/100} END {printf "Total = %.2f\n", total}' data

Output:

BPRC000000000008801     88.01
BPRC000000000006671     66.71
BPRP000000000005088     50.88
BPRC000000000004542     45.42
BPRP000000000003805     38.05
BPRC000000000013624     136.24
BPRC000000000235668     2356.68
Total = 2781.99

Upvotes: 1

Birei
Birei

Reputation: 36252

Try with two sub() functions. The first one to remove all characters until a non-zero number. And the second one to add the decimal point:

awk '
    BEGIN { OFS = "\t" } 
    { $2 = $1; 
      sub( /^[^0]*0*/, "", $2 ); 
      sub( /..$/, ".\&", $2 ); 
      print $0 
    }
' data

It yields:

BPRC000000000008801     88.01
BPRC000000000006671     66.71
BPRP000000000005088     50.88
BPRC000000000004542     45.42
BPRP000000000003805     38.05
BPRC000000000013624     136.24
BPRC000000000235668     2356.68

Upvotes: 1

Related Questions