Multiply values from a file

Hi All,

I extracted a file using an awk command like this

awk '{print substr($0,78,5)"," substr($0,59,6) ","  substr($0,81,3) "," substr($0,11,7)}'  file1 >> OUTPUT
cat OUTPUT
00001,100000,005,0000080
00001,100000,008,0000220
00001,100000,001,0001000
00010,100000,001,0000400

I want to do some math operation on the record in that file. I need do below operation

((COLUMN1*COLUMN2)/10000.0)*COLUMN3*(COLUMN4/1000.0)

I did the below operation to test the multiplication and I get some error. Can you help please

cut -d"," -f1*f2 OUTPUT
cut: invalid byte, character or field list
Try 'cut --help' for more information.

Thanks
Arun

Why not use awk for the arithmetics as well?

1 Like

Thanks the below worked . Is there a way I can sum those values to total. I get the each row doing the operation but I need to sum up those rows

awk '{print  (  ( substr($0,50,5) * substr($0,55,6) /100000 )*  substr($0,88,3)  * ( substr($0,81,7) /1000))          }

Hi, try:

awk '
  {
    result=substr($0,50,5) * substr($0,55,6) * substr($0,88,3) * substr($0,81,7) / 10^8
    tot+=result
    print result
  } 
  END {
    print tot
  }
' file

In GNU awk, you can also do this:

awk -v FIELDWIDTHS="49 5 6 20 7 3 99"  '
  {
    result=$2 * $3 * $6 * $5 / 10^8 
    tot+=result
    print result
  } 
  END {
    print tot
  }
' file
1 Like