Justin
Justin

Reputation: 11

performing arithmetic on variables set by while-read loop

I want to perform some arithmetic and floating point arithmetic operations on some variables that I read in from a while loop. My code looks like this:

while read n p qlen slen len; do 

    random_var=$(( $qlen + 0 )) # gives all zeros, not saving qlen

    qcov=$(echo $len / $qlen | bc -l) #len and qlen are nothing, not working

    qcov=$( bc  <<< "scale=3; $len / $qlen" ) #same reason as above, not working

done < input_file.txt       

I am pulling each line in input_file.txt and parsing the data into their respective variable names, n, p, qlen, slen, and len. The input file input_file.txt looks like this:

test1 12.345 123 234 12
test2 23.456 345 678 43
test3 98.765 6537 874 346
...

The problem I am having is when I try to perform some arithmetic operation on any of the variables from the read. I can echo the variables just fine, but as soon as I try to perform any kind of arithmetic manipulation, the values are nothing. I suspect that they are not numerals to begin with, some sort of string type (?). I've tried many integer and floating point arithmetic statements and can't seem to preserve the values in the variables. bc commands, arithmetic expansion, echo piped into bc, the triple <<< for bc, all of these solutions I've found online do not work.

The most common errors I receive are:

I've thought about using an awk but I need to perform these operations on every line, and awk keeps going until the end of the file. Is there still a way to do what I want using an awk? I don't really know.

If anyone has an answer or an alternative way to pull data out of the file, I'd really appreciate it.

Thanks in advance.

UPDATE:

some fiddling around with the code has made me realize that everything in the input_file.txt is being saved into only the first variable n. This is why the other variables are empty and why the echo of all the variables looked correct.

Any ideas why the values are not being saved into the correct variables?

Upvotes: 0

Views: 138

Answers (1)

Diego Torres Milano
Diego Torres Milano

Reputation: 69198

I don't know what you really want to obtain. but it seems something like

awk '{print $5/$3}' input_file.txt 
0.097561
0.124638
0.0529295

Upvotes: 1

Related Questions