Question

I have a lot of tracks in iTunes where the files are named "music-NNNN.mp3" with NNNN being the year the track was recorded. How can I use Applescript to automatically set the year tag for these files based on NNNN?

Was it helpful?

Solution

I created an AppleScript for you that will parse the filenames of any selected iTunes tracks and set the year tag accordingly.

Paste this into AppleScript Editor and run it (or save it as an application):

tell application "iTunes"
    repeat with theTrack in selection
        set theFile to location of theTrack
        tell application "Finder" to set theName to name of theFile
        set theYear to my parse_year(theName)
        if theYear is not "" then
            set the year of theTrack to theYear
        end if
    end repeat
end tell

on parse_year(filenameText)
    -- returns the year if it exists in filename with form song-1965.mp3, else returns empty string
    try
        set yearResult to do shell script "echo " & quoted form of filenameText & " | perl -ne 'print $1 if s/(?<=-)(\\d+)(?=(\\..*|$))/$1/'"
    on error
        set yearResult to ""
    end try
    return yearResult
end parse_year

A few notes:

  • It doesn't go through the whole library, only the currently selected songs (you can of course select your whole library).
  • It only matches filenames with that end with a - followed by a number (and optionally an extension).

    • It will match these:

      songname-1946.mp3
      anothersong-1977
      songname-1965.someextention
      
    • But not these:

      songnoyear.mp3
      song123
      song-1232-someothertext
      
  • It will overwrite any year already entered in the metadata.

OTHER TIPS

set text item delimiters to {"-", "."}
tell application "iTunes"
    repeat with t in selection
        set year of t to text item -2 of (location of t as text)
    end repeat
end tell

Unlike many other command line utilities for changing ID3 tags, mid3v2 supports both Unicode and ID3v2.

sudo easy_install pip
sudo pip install mutagen
for f in */*.mp3; do y=${f%##*/}; y=${y%.mp3}; /usr/local/bin/mid3v2 -y ${y#*-} "$f"; done

You can also use TriTag for changing tags based on file names or vice versa.

Licensed under: CC-BY-SA with attribution
Not affiliated with apple.stackexchange
scroll top