1

I am trying to do a simple division computation between two integers that will result in a float. I do not want to use bc. This approach works for me for a different purpose with slightly different syntax but I am not quite sure where I am messing up. I am positive that the variables are getting assigned correctly, but I have an error once I try to do the division, and nothing actually gets assigned to the variable. Can anyone help?

Thanks in advance!

rate=`awk '{ shared = "'"${tempRatioArray[0]}"'"; total = "'"${tempRatioArray[1]}"'";\ printf "%3.0f\t", shared/total }' | awk '{print}'` 
3
  • 2
    Why don't you want to use 'bc' given that it seems quite suitable ? Commented Jul 9, 2014 at 16:29
  • I need to be consistent-- this is code that I am using for my thesis and I am on the tail end!! We had issues previously with bc properly handling variables so our workaround was awk and so far it has been working as expected! Commented Jul 9, 2014 at 17:01
  • Perhaps this is usefull: stackoverflow.com/a/24431665/3776858 Commented Jul 9, 2014 at 17:26

2 Answers 2

3

You can use bc:

bc -l <<<"scale=3; 5/2" 2.500 

Adapting to your code:

bc -l <<< "scale=3; ${tempRatioArray[0]} / ${tempRatioArray[1]}" 
Sign up to request clarification or add additional context in comments.

Comments

2

That is not correct way of using shell variables in awk and you don't need 2 awk commands.

Use it like this:

rate=$(awk -v shared="${tempRatioArray[0]}" -v total="${tempRatioArray[1]}" 'BEGIN { printf "%.3f", (shared/total) }') 

4 Comments

Thank you for the response! I have tried this: rate=awk -v shared="${tempRatioArray[0]}" -v total="${tempRatioArray[1]}" 'BEGIN { printf "%3.0f\t", (shared/total) }'`` but the rate comes out to equal 0...
Can you run: awk -v shared="${tempRatioArray[0]}" -v total=${tempRatioArray[1]}" 'BEGIN { printf "[%s][%s]%3.0f\n", shared, total, (shared/total) }' and tell me its output.
The output is this: val for LLC ratio: 5100566 75873367 rate = [5100566][75873367]3.0f ./LLC_resource_migrate.sh: line 204: [: [5100566][75873367]3.0f: integer expression expected
Great to know, can you mark the answer as accepted by clicking on tick mark on top-left of my answer.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.