floating-point operations with bash

淺唱寂寞╮ 提交于 2019-12-09 10:54:44

问题


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


回答1:


Use bc -l

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

OR awk:

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



回答2:


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


来源:https://stackoverflow.com/questions/20718482/floating-point-operations-with-bash

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!