简体   繁体   中英

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.

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

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

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}'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM