Saturday·27·November·2010
Useful but Unknown Unix Tools: units //at 14:56 //by abe
Ever wondered how to easily convert e.g. 10 seamiles into kilometres? Use units:
$ units 2411 units, 71 prefixes, 33 nonlinear units You have: 10 seamiles You want: km * 18.288 / 0.054680665 You have: ^C $
Of course this is interactive. There’s also a non-interactive mode:
$ units '10 seamiles' 'km' * 18.288 / 0.054680665 $
The line with the asterisk means that 10 seamiles are 18.288 kilometres or 1 kilometre is the 0.054680665th part of 10 seamiles.
This quite non-intuitive output is caused by the fact that unit is designed to be used with units only:
$ units seamiles km * 1.8288 / 0.54680665 $
Now this makes more sense: You have to multiply seamiles with 1.8288 to get kilometres and you have to multiply (not divide) kilometres with 0.54something to get seamiles.
But this output is still a little bit cumbersome, and annoying if you want to use it in shell scripts. But for luck, units knows some nice options, especially “-v” (“–verbose”) and “-t” (“–terse”):
$ units -v '10 seamiles' km 10 seamiles = 18.288 km 10 seamiles = (1 / 0.054680665) km $ units -t '10 seamiles' km 18.288
Now that’s way easier to read and script!
You can also script more complex things like
$ units -v '100 attoparsec/microfortnight' m/s 100 attoparsec/microfortnight = 2.5509901 m/s 100 attoparsec/microfortnight = (1 / 0.39200466) m/s
Unfortunately not all common units are unambiguous for units:
units -v '100 km/h' m/s conformability error 100 km/h = 1.5091905e+38 s / kg m m/s = 1 m / s
Well, “h” seems not to be units unit for “hours”, so lets tell it explicity that we want km per hour:
units -v '100 km/hour' m/s 100 km/hour = 27.777778 m/s 100 km/hour = (1 / 0.036) m/s
Looks more like what I expected.
“units” behaves though a little bit strange when I try to convert litres per 100 kilometres into miles per gallon:
$ units -t '6L/100km' 'mpg' conformability error 6e-08 m^2 425143.71 / m^2 $
Interestingly changing the verbosity helps already in this case:
$ units -v '6L/100km' 'mpg' reciprocal conversion 1 / (6L/100km) = 39.202431 mpg 1 / (6L/100km) = (1 / 0.025508622) mpg
Greetings from the Debian booth at LinuxDay.at and thanks to Y_Plentyn, rhalina and bzed
for example ideas and the suggestion to write a blog posting about
units. :-)
Tagged as: bzed, CLI, conversion, LinuxDay.at, rhalina, units, UUUT, Y_Plentyn
4 comments // show without comments // write a comment