user4336241
user4336241

Reputation:

Bash arithmetic expression with variable

I'm writing a small bash script to treat my data.

In part of the script, I need to use the data, which exists in my raw data, to generate a new value.

However, the script I wrote does not work.

The terminal gives me the following error

")0.192500rror: invalid arithmetic operator (error token is "

the value of each variable is: inc= 0.0200000, str= -0.192500, pts= 1024,

My script is as follows:

for i in *.TXT; do

    inc=$(sed -n '/^#XPERCHAN/ p' $i | sed 's/[A-Z:# ]//g')
    str=$(sed -n '/^#OFFSET/ p' $i | sed 's/[A-Z:# ]//g')
    pts=$(sed -n '/^#NPOINTS/ p' $i | sed 's/[A-Z:# .]//g')
    lst=$(( ($pts-1)*$inc+$str))
    echo $lst

done

Please help me out here. Thanks!

Upvotes: 0

Views: 380

Answers (1)

Amadan
Amadan

Reputation: 198324

bash only knows integers. Use bc or a higher programming language for floats.

lst=$(echo "($pts - 1) * $inc + $str" | bc)

EDIT: If your file is formatted like I think it is (#XPERCHAN: 0.0200000), you can do all of that in one awk:

lst=$(awk '/^#XPERCHAN/ { inc=$2 } /^#OFFSET/ { str=$2 } /^#NPOINTS/ { pts=$2 } END { print ((pts + 1) * inc + str) }' $i)

Upvotes: 2

Related Questions