0

I had a bunch of media (videos to be precise) in a folder and I wanted to sum all the lenghts. I'll be ignoring seconds and hours for now, just to get the gist of it. I wrote this script:

sum=0
for file in *
do
curr=$(exiftool $file |
   grep -i "^Duration" |
   awk '{print $3}' |
   cut -d':' -f 2)
((sum = sum + curr))
done
echo $sum

But it was really slow, and I wondered if I could somehow make it faster (or alter it, I'm wondering if how would you do it differently).

Logic behind it is pretty straightforward, iterate through every file in directory, grab lines with duration, isolate time (hh:mm:ss) format with awk, cut with ':' as delimiter to isolate minutes. And add the minutes together in process, and print the sum. I'm using zsh for the record.

Fedja M.
  • 105
  • 8

1 Answers1

3

You could simplify it to:

exiftool -n -q -p '${Duration;$_ = ConvertDuration(our $total += $_)}' ./*(-.) |
   tail -n 1

(as per Get total duration of video files in a directory, here using *(-.) since you're using zsh, to limit to regular files or symlinks to regular files).

The duration here is properly calculated as with -n we get the raw seconds, and only we only do the fancy formatting after doing the summing.

In any case, the slow part is likely to be mostly down to exiftool itself. At least here, it's invoked only once which should bring some improvement.

Also note that awk can do both grep's and cut's work as well as do sums, so if exiftool couldn't do the calculation itself, you could still simplify it do:

exiftool -q -n -Duration ./*(-.) | awk -F: '{sum += $2}; END{print sum/60}'

for the total duration in minutes.

Stéphane Chazelas
  • 522,931
  • 91
  • 1,010
  • 1,501