Extracting ID3 tags from the command line - two methods

As part of a Hazel rule to process downloaded mp3 files, I worked out a couple different methods for extracting the ID3 title tag. Not rocket science, but it took a little time to sort out. Both rely on non-standard third-party tools, both for parsing the text and for extracting the ID3 tags.

Extracting ID3 title with ffprobe

ffprobe is part of the ffmpeg suite of tools which on macOS can be installed with Homebrew. If you don’t have the latter, go install it now; because it opens up so many tools for your use. In this case, it makes ffmpeg available via brew install ffmpeg.

With that in place, extracting the title is just:

title=$(ffprobe -loglevel error -show_entries format_tags=title -of 
   default=noprint_wrappers=1:nokey=1 $file)

Extracting ID3 title with id3info

id3info is part of the id3tool suite of tools installed using - you guessed it - Homebrew. This solution also uses sd (brew install sd.) The latter is a more intuitive search and displace tool than the old stand-by sed.

IFS=$'\r\n'
tit2=""
for ln in $( id3info $file ); do
    if echo $ln | grep -q "TIT2"
    then
        tit2=$( echo $ln | sd '.*TIT2.*: (.*).*' '$1' );
        break;
    fi
done

Or a one-liner using perl:

echo $( id3info $file ) | perl -ne 'print $1 if /TIT2.*?\:\s+(.*?)\s===/;'

References

  • sd - intuitive search and displace - a sed replacement
  • ffmpeg - play, record, convert, and stream audio and video
  • id3tool - ID3 editing tool
  • Bash for loop - a short tutorial on the Bash for loop - something that I wasn’t really proficient at. Always good to revist.

Using variables in Keyboard Maestro scripts

Having fallen in love with Keyboard Maestro for its flexibility in macOS automation, I began experimenting with scripting in various languages, like my old favourite Perl. That’s when the fun began. How do we access KM variables inside a Perl script.

Let’s see what the documentation says:

So the documentation clearly states that this script

#!/usr/bin/perl

print scalar reverse $KMVAR_MyVar;

should work if I have a KM variable named MyVar. But, you guessed it - it does not.

After digging around in the Keyboard Masestro forums, I found an obscure post that pointed the way. It turns out that the Perl access to KM variables is completely different from what the documentation claims, the format is not $KMVAR_MyVar, it is actually:

$ENV{KMVAR_MyVar}

so the above script works if the variable is accessed from Perl that way:

#!/usr/bin/perl

print scalar reverse $ENV{KMVAR_MyVar};