Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mm:ss calculator from shell prompt?

From a shell prompt, what's the fewest-keystrokes way to calculate the mm:ss value of expressions such as 4:33 + 0:20 - 2:45 = 2:08 ?

This is for interactive use, not for use in a script, or measuring elapsed time, or anything fancy like that. No mouse. No GUI.

There are thousands of implementations of mm+60*ss and (mmss/60, mmss%60), in hundreds of languages. I could write a script in bash or ruby or C for this, to add yet another implementation. But it seems likely that this wheel doesn't need reinventing, when it's likely buried somewhere in bc, dc, irb, or maybe even in bash itself.

like image 286
Camille Goudeseune Avatar asked Dec 22 '14 15:12

Camille Goudeseune


1 Answers

Although not perfect:

s="4:33 + 0:20 - 2:45"
n=$(sed 's/\([0-9]*\):\([0-9]*\)/(\1 * 60 + \2)/g' <<< "$s" | bc)
printf "%d:%02d\n" $(( $n / 60 )) $(( $n % 60 ))

The sed command outputs (4 * 60 + 33) + (0 * 60 + 20) - (2 * 60 + 45) to bc.

The output is: 2:08.

like image 164
perreal Avatar answered Nov 05 '22 06:11

perreal