renaming finder items III

renaming finder items introduced a couple of ways to batch-rename files in the finder — using automator or applescript — by replacing characters or removing parts of the file name. renaming finder items II showed how to map a bunch of files to a completely different set of file names.

Applescript Icon this post will show another way to rename files — based on their creation date — using applescript. this workflow came about due to the diabolical way that digital cameras name their files. here’s a screen grab of a typical bunch of images :
screen grab of folder of images with diabolical file names

for this workflow, we’d like the order of the filenames to match the date the photo was taken — to make sorting, selecting, archiving, etc. just a little easier. the current naming is made more problematic because files are coming from more than one camera. well, we don’t have to put up with that crap — let’s just rename them.

set mgFolder to choose folder
tell application "Finder"
  set mgFiles to items of mgFolder
end tell
repeat with mgFile in mgFiles
  set mgPath to POSIX path of (mgFile as string)
  set mgCreation to creation date of mgFile
  set mgDate to short date string of mgCreation
  set mgTime to time string of mgCreation
  
  -- rest of script here
end repeat

first we get the user to select a folder of images to process, then we get references to the files in that folder, then we start a repeat loop to process each file in turn. we capture the following information :
mgCreation – for example “Thursday, 4 October 2012 17:13:18 ” – from which we extract :
mgDate – “04/10/12” (that’s dd/mm/yy) and
mgTime – “17:13:18 ” (that’s hh/mm/ss)

if you find that mgDate or mgTime give you the data in a different format, you will need to update the next part of the script accordingly or, if you prefer, change your language and text system preferences :
screen grab showing language and text system preferences window

we’re going to use mgDate and mgTime to create a file name like this “yymmdd_hhmmss” — so, we need to strip out the slashes and colons, reverse the order of the date, and introduce an underscore :

  set text item delimiters of AppleScript to ":"
  set mgTime to text items of mgTime --gives {"17", "13", "18 "}
  set text item delimiters of AppleScript to "/"
  set mgDate to reverse of text items of mgDate --gives {"12", "10", "04"}
  set text item delimiters of AppleScript to ""
  set mgDate to mgDate as string --gives "121004"
  set mgTime to mgTime as string --gives "171318 "
  set mgTime to text items 1 thru 6 of mgTime as string
  
  set mgNewName to mgDate & "_" & mgTime

this uses the handy “reverse of” command — taking a list of items and rearranging them in reverse order. also notice the second last line — we need that because mgTime has a trailing space we need to get rid of. this method works no matter how many trailing spaces there are because we’re saying “just give me the first six characters and ditch the rest”.

now, that’s the bulk of the script done — we also need to capture the extension of the file (mgExtension), create a filepath for the renamed file (mgFinalPath), and then do the renaming with a shell script. the shell script basically says — move this file, without any prompts, from this filepath to that filepath (you could also use this method to move the file to a completely different location — but we’re just renaming the file and leaving it in the same location) :
danger : do not run this next script — it is for demonstration purposes only – you’ve been warned!

set mgFolder to choose folder
tell application "Finder"
  set mgFiles to items of mgFolder
end tell

repeat with mgFile in mgFiles
  set mgPath to POSIX path of (mgFile as string)
  set mgCreation to creation date of mgFile
  set mgDate to short date string of mgCreation
  set mgTime to time string of mgCreation
  
  set text item delimiters of AppleScript to ":"
  set mgTime to text items of mgTime
  set text item delimiters of AppleScript to "/"
  set mgDate to reverse of text items of mgDate
  set text item delimiters of AppleScript to "."
  set mgExtension to text item -1 of (mgFile as string)
  set text item delimiters of AppleScript to ""
  set mgDate to mgDate as string
  set mgTime to mgTime as string
  set mgTime to text items 1 thru 6 of mgTime as string
  
  set mgNewName to mgDate & "_" & mgTime

  set mgFinalPath to mgFolder & mgNewName & "." & mgExtension as string

  do shell script "mv -f " & quoted form of POSIX path of mgPath & space & quoted form of POSIX path of mgFinalPath
end repeat

if we run this script on that original folder of images we’ll get this :
screen grab of file names after processing with first script

well, that looks pretty good at first glance — all the files have been renamed successfully … except … the very observant will notice that this folder has only 81 items, whereas the original folder had 103. wtf?

the problem is that it’s quite possible to have more than one file with a creation date of “04/10/12 17:13:18” — digital cameras can flick off quite a few images in a second. the script in its current form will simply write over a file with a duplicate filename. so we need to build in some method to check if a file with a particular name already exists and, if so, create a different name. here’s one way :

  set mgFinalPath to mgFolder & mgNewName & "_1" & "." & mgExtension as string
  tell application "Finder"
    set x to 2
    repeat
      set mgExists to exists file mgFinalPath
      if mgExists is true then
        set mgFinalPath to mgFolder & mgNewName & "_" & x & "." & mgExtension as string
        set x to x + 1
      else
        exit repeat
      end if
    end repeat
  end tell

this time we’re appending “_1” to each filename. then the script enters a repeat loop to check if a file with that name already exists. if so, it will change the end to “_2” and then check that, incrementing by one on each pass through the loop. once it reaches a name that has not already been used it exits the repeat loop. this way we don’t lose any files :
screen grab of filenames using final script

this is the final form of the script. it’s always a good idea to test new scripts on duplicate files before implementing them into your workflow — just to make sure they do what you expect (and don’t do what you don’t expect) — you’ve been warned again :

set mgFolder to choose folder
tell application "Finder"
  set mgFiles to items of mgFolder
end tell

repeat with mgFile in mgFiles
  set mgPath to POSIX path of (mgFile as string)
  set mgCreation to creation date of mgFile
  set mgDate to short date string of mgCreation
  set mgTime to time string of mgCreation
  
  set text item delimiters of AppleScript to ":"
  set mgTime to text items of mgTime
  set text item delimiters of AppleScript to "/"
  set mgDate to reverse of text items of mgDate
  set text item delimiters of AppleScript to "."
  set mgExtension to text item -1 of (mgFile as string)
  set text item delimiters of AppleScript to ""
  set mgDate to mgDate as string
  set mgTime to mgTime as string
  set mgTime to text items 1 thru 6 of mgTime as string
  set mgNewName to mgDate & "_" & mgTime
  
  set mgFinalPath to mgFolder & mgNewName & "_1" & "." & mgExtension as string
  tell application "Finder"
    set x to 2
    repeat
      set mgExists to exists file mgFinalPath
      if mgExists is true then
        set mgFinalPath to mgFolder & mgNewName & "_" & x & "." & mgExtension as string
        set x to x + 1
      else
        exit repeat
      end if
    end repeat
  end tell
  
  do shell script "mv -f " & quoted form of POSIX path of mgPath & space & quoted form of POSIX path of mgFinalPath
end repeat

now, of course, you can run this script for any kind of file, not just images. but in its current form it has no error handling for if it encounters a folder. we’ve fixed it so it won’t have a hassle with duplicate files, but if it hits a folder you’ll get something like this :
screen grab of error message if script encounters a folder

dammit you say. but the fix is actually very simple — just change the line “set mgFiles to items of mgFolder” to “set mgFiles to files of mgFolder” and the folders will be skipped — no drama.

but that’s not all …
just to be safe, or because your workflow calls for it — you could change the script so that it makes a copy of the file — giving the new name to the copy and leaving the original untouched.

and again, the solution is very simple — change the shell script from move (mv) to copy (cp) :

do shell script "cp -f " & quoted form of POSIX path of mgPath & space & quoted form of POSIX path of mgFinalPath

you can get a copy of the RenameByDate app here

keep grunting


• related post : renaming finder items : renaming using automator or applescript.
• related post : renaming finder items II : renaming by list.
• related post : renaming finder items IV : easy renaming.

macgrunt icon

Advertisements

renaming finder items II

renaming finder items introduced a couple of ways to batch-rename files in the finder using either automator or applescript, depending on the complexity of the job. those examples involved altering the existing filename by replacing characters or removing parts of the name. here’s another renaming workflow that was developed when one set of filenames needed to be mapped to a completely different set — hundreds of barcodes named by ISBN needed to be renamed by product code.

Applescript Icon applescript is fantastic for this kind of work because renaming hundreds of files by hand is just about as tedious as it gets. as with most scripting tasks, there are myriad ways this problem could be tackled — here’s just one :

screen grab showing filenames in excel

this solution starts with two lists — original filenames and new filenames — in a single excel worksheet. for this version of the app to work correctly, the worksheet needs to be saved in the same folder as the files to be changed and the worksheet needs to be open in excel.

the app looks through the top level of the folder for files and folders matching the names in column A and changes the filenames to the corresponding ones in column B — simple. files that don’t match a name in the list are skipped. all original file extensions are maintained. files in subfolders remain untouched. here’s a before and after shot of test files :

screen grab showing files before and after name changes

RenameByList is a zipped folder containing the app and a sample excel file. to use it — update the excel spreadsheet to your requirements, put all your files in the same folder and double-click the app :

you can get a copy of RenameByList here

screen grab showing compiled script in script editor

for those interested in this sort of thing…
excel can be a bit of a pain to script. for example, this is the command to extract the entries in column A :
set mgANames to formula of range mgARange

instead of giving us a list of names :

{"9781234567890", "9781234567891", "9781234567892" ...

this command gives us a list of lists :

{{"9781234567890"}, {"9781234567891"}, {"9781234567892"} ...

that’s why we need to loop through the original list (mgANames) with this command — to convert the list of lists into a straight list :
set end of mgOriginalNames to item 1 of item x of mgANames

the other way would be to just loop through the cells in excel to make the list in one pass like this :

tell used range to set mgRowCount to count rows
repeat with x from 2 to mgRowCount
  set end of mgOriginalNames to formula of cell ("A" & x)
  set end of mgNewNames to formula of cell ("B" & x)
end repeat

but this script was developed and tested through script editor before being saved out as an app. and this second method is MUCH slower through script editor (although not much different when run as an app). try it yourself.


• related post : renaming finder items : renaming using automator or applescript.
• related post : renaming finder items III : renaming by creation date.

macgrunt icon