0

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!

1 Answer 1

2

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)
Sign up to request clarification or add additional context in comments.

5 Comments

I used your code, it returns me the following: (standard_in) 1: illegal character: ^M (standard_in) 1: illegal character: ^M (standard_in) 1: illegal character: ^M
That means your file is made on Windows, and your sed didn't clean it up well enough. Either add \r to the list of the characters to filter out, or use the awk method (which will not pick it up in the first place).
I used your EDIT, it works perfectly! Thanks! I still would like to know why the 1st way gave me that error.
Thanks again! I got it!
As I said, Windows. In Windows (and MSDOS), line ends with \r\n (CR LF, ^M^J, lots of ways to write it.) In Linux, a line ends with \n (LF, ^J), and \r (^M) is just another character. So when you delete all A-Z:# and spaces from it, ^M is still there, at the end; and bc doesn't like it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.