Search code examples
linuxawkarithmetic-expressions

how to do arithmatic operations in linux using awk or sed and piping the result to a file


with this problem I am beating my head with walls, please help.

I have two files Sheetthickness.k which contains a single value of initial thickness and minThick.k which contains the final thickness only a single number. I want to calculate the percentage decrease in thickness so I used.

fina="$(cat minThick.k)";
echo $fina
init="$(cat Sheetthickness.k)";
echo $init 

echo |awk "{ print ($init-$fina)/($init) }" > LSDynaResponse.txt

In shell where there is no other command and the files are already there then it works perfectly , but when the files are created by a software and then these commands are used, it gives error.

awk: { print (-)/() }  
awk:           ^ syntax error
awk: { print (-)/() }
awk:            ^ syntax error
awk: { print (-)/() }
awk:             ^ unterminated regexp

Any other elegant way to do this task?


Solution

  • It sounds like you have empty files or no files at all, try like this:

    fina="$(cat minThick.k)"       || echo "No min file!!"
    [[ -z $fina ]]                 && echo "Null min value!!"
    echo $fina
    init="$(cat Sheetthickness.k)" || echo "No init file!!"
    [[ -z $init ]]                 && echo "Null init value!!"
    echo $init
    echo "($init-$fina)/($init)"   | bc -l > LSDynaResponse.txt