2

I currently have a function that prints the position and duration from cmus and formats it like "1/500". The issue I'm having is that I would like the position and duration data to be presented in minutes as opposed to seconds (0:01/8:20 instead of 1/500) but I'm out of ideas on how to achieve this.

Currently the relevant part of the function looks like this:

print_music(){
    if ps -C cmus > /dev/null; then
        position=`cmus-remote -Q |
            grep --text '^position' |
            sed -e 's/position //' |
            awk '{gsub("position ", "");print}'`
        duration=`cmus-remote -Q |
            grep --text '^duration' |
            sed -e 's/duration //' |
            awk '{gsub("duration ", "");print}'`
        echo "[$position/$duration]"; else echo "";
    fi
}
αғsнιη
  • 40,939
  • 15
  • 71
  • 114
Joe
  • 37
  • 1
  • 5

2 Answers2

9

This will help you:

sec2min() { printf "%d:%02d" "$((10#$1 / 60))" "$((10#$1 % 60))"; }
$ sec2min 500
8:20
$ sec2min 1
0:01
glenn jackman
  • 84,176
  • 15
  • 116
  • 168
  • Here's the same operation using a second iteration of awk ... `awk '{ min = ($1 / 60)-(($1 % 60)*1/60) ; sec = $1 % 60 ; print min,":",sec}'` – RubberStamp Apr 03 '19 at 00:41
0

I was trying to accomplish the exact same thing. Using the awk method from @RubberStamp's comment on @glenn jackman's answer I ended up with the following which displays: e.g.

2:07 / 4:08

cmus-remote -Q | egrep "^duration|position" \
| tr '\n' ' ' \
| sed "s#^duration \|position ##g" \
| awk '{print ($2 / 60)-(($2 % 60)*1/60) ":" ($2 % 60), "/", ($1 / 60)-(($1 % 60)*1/60) ":" ($1 % 60)}' \
| sed "s#:\([0-9]\)\( \|\$\)#:0\1\2#g#";

Note: the last sed expression adds in leading 0s so that 2:7 / 4:8 displays properly as 2:07 / 4:08 instead.

twhitney
  • 11
  • 3