1

I am reading values from an text file:

input=$(head -52 file.txt | tail -1 | cut -f2 | awk '{print $3}' )

I get the 3rd word of the 52 line of the file, which is:

576.00

However I need the input value as an integer. (only 576 instead of 576.00) Then I need to divide the input value by 3 and assign the closest integer to the calculation to the variable output:

output=$((input / 3))

Of cures the line about won't work because the answer is not an integer. any ideas?

3 Answers 3

2

Just change your awk to:

awk '{print int($3)}' 

this will now output 576

OR you can do division in awk itself:

input=$(head -52 file.txt | tail -1 | cut -f2 | awk '{print int($3)/3}' )
Sign up to request clarification or add additional context in comments.

1 Comment

Might as well do all of the extraction in Awk. See user's previous question about this: stackoverflow.com/a/21031654/874188
1

Why not clean up the whole line and let awk do the job:

input=$(awk 'NR==52 {print int($3)/3}' file.txt)
echo $input
192

If file is huge, you can jump out of it when job done:

awk 'NR==52 {print int($3)/3;exit}'

1 Comment

+1 for the complete solution. I'd have thought int($3/3) would be the desired output though.
0

You could just remove the decimal part of it:

input=$(head -52 file.txt | tail -1 | cut -f2 | awk '{print $3}' | cut -d '.' -f 1)

Combine that with a Bash rounding function, and you're golden.

However, why you would cut off the decimal part ("floor" the value) before dividing it and rounding the answer is beyond me. For example, using equivalent Python code:

>>> import math
>>> round(math.floor(4.99)/3, 0) == 1
True
>>> round(4.99/3, 0) == 2
True

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.