A nice challenge!
Here is the one-liner:
printf "%02d:%02d:%02d\n" $((($(for f in *.mp4;do ffprobe "$f" 2>&1|awk '/Duration:/{d=substr($2,1,8);split(d,t,":");print t[1]*3600+t[2]*60+t[3]}';done|awk '{t+=$1}END{print t}')/3600)) $(((($(for f in *.mp4;do ffprobe "$f" 2>&1|awk '/Duration:/{d=substr($2,1,8);split(d,t,":");print t[1]*3600+t[2]*60+t[3]}';done|awk '{t+=$1}END{print t}')%3600)/60)) $((($(for f in *.mp4;do ffprobe "$f" 2>&1|awk '/Duration:/{d=substr($2,1,8);split(d,t,":");print t[1]*3600+t[2]*60+t[3]}';done|awk '{t+=$1}END{print t}')%60))
Ugh, I know, it's ugly! But it works!
Explanation:
I simply:
- Copied the
for loop and the two awk commands from the original first line (the one that calculates the total seconds t).
- Embedded this entire pipeline inside the
$(( )) arithmetic expansion, three times (for hours, minutes, and seconds calculations).
- Replaced
t with the entire pipeline, so that its output (the total seconds) is used in the calculations.
How to make it slightly less unreadable:
Use a variable to store the duplicated pipeline:
p="for f in *.mp4;do ffprobe \"$f\" 2>&1|awk '/Duration:/{d=substr(\$2,1,8);split(d,t,\":\");print t[1]*3600+t[2]*60+t[3]}';done|awk '{t+=\$1}END{print t}'"
printf "%02d:%02d:%02d\n" $((($(eval $p)/3600)) $(((($(eval $p)%3600)/60)) $((($(eval $p)%60))
Here, I:
- Stored the pipeline in
p, escaping " and $ to prevent early expansion.
- Used
eval to execute the stored pipeline, three times.
Still not beautiful, but a bit more manageable.
The real solution:
If you need to do this often, consider turning the logic into a shell function:
total_duration() {
for f in *.mp4; do
ffprobe "$f" 2>&1 | awk '/Duration:/{d=substr($2,1,8);split(d,t,":");print t[1]*3600+t[2]*60+t[3]}'
done | awk '{t+=$1}END{print t}'
}
t=$(total_duration)
printf "%02d:%02d:%02d\n" $((t/3600)) $(((t%3600)/60)) $((t%60))
Now, that's readable and maintainable!
Choose your poison!