11

how can I transform the string "620/100" into "6.2" in a bash script

The context of my question is about image processing. EXIF data are coding the focal length in fractional format, while I need the corresponding decimal string.

Thanks for helping, Olivier

4 Answers 4

23

Use bc -l

bc -l <<< "scale=2; 620/100"
6.20

OR awk:

awk 'BEGIN{printf "%.2f\n", (620/100)}'
6.20
0
6

bash doesn't support floating point.

You could use bc:

$ echo "50/10" | bc -l
5.00000000000000000000
$ echo "scale=1; 50/10" | bc -l
5.0
3

Thank-you for the answers. bc was what I needed.

I dont know if posting the result is of any use. Anyway, this the final piece of code for exteracting the focal length of a photo and print it in decimal format. It is supposed to work for all cameras. Tested on 4 cameras of 3 different brands.

F="your_image.JPG"
EXIF=$(exiv2 -p v "$F")
FocalFractional=$( echo "$EXIF" | grep -E '[^ ]*  *Photo *FocalLength '| grep -iohE "[^ ]* *$" )
Formula="scale=2; "$FocalFractional
FocalDecimal=$( bc -l <<< "$Formula" )
echo $ FocalDecimal
1

bc -l <<< 100/3 really helped me also. Thanks a lot. But if someone have to use variables to perform decimal arithmetic and the result has to be saved in a new variable, then try the below syntax: answer=$(bc -l <<< $num_1*$num_2)

2
  • Please don't add "thank you" as an answer. Once you have sufficient reputation, you will be able to vote up questions and answers that you found helpful. - From Review
    – mana
    Mar 1, 2023 at 19:36
  • This type of commentary is better provided as a comment on the question or answer that you are responding to, rather than as an answer itself. Mar 1, 2023 at 22:49

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.