Apple Script to rename file according to delimiters and regular expressions

Discussion in 'Mac Programming' started by kai-uwe-heinz, Sep 12, 2015.

  1. kai-uwe-heinz macrumors newbie

    Sep 12, 2015
    Hi there,

    I want to create an AppleScript to rename a selection of files that have the following pattern:
    "YYYY-MM-DD [file name referring to content, variable in length] HH-MM-SS.pdf"

    (with some of the files lacking the time stamp at the end, others the date stamp at the beginning which in some cases has only the pattern YYYY-MM)

    into the pattern "[file name].pdf"

    I must admit I am new but have built some small scripts by pasting and copying and modifying what I found in several forums.

    I'd procede like this:
    I'd tell finder which files to grab:

    Get-ChildItem C:\Path\To\Files *.pdf |

    now I'd like to tell finder:
    filename starts with a number
    search for the delimiter " "

    and select all characters before it and delete it /replace this selection with ""

    then check if the 8th character before ".pdf" is a number (or otherwise if the 5th one is a number and if so to select the items between the 8th (or 5th) character and the last delimiter "." and erase them.

    How would I do this practically? Who can help?

  2. cqexbesd macrumors regular

    Jun 4, 2009
    I don't know AppleScript but it can be done easily in many other scripting systems and if you have existing AppleScript code you could call out to one of them - if not just avoid AppleScript.

    This should work if you are in the same directory as the files. If not it should need only small changes to the regex.

    perl -E 'foreach $name (@ARGV) { if ($name =~ /^\d{4}-\d{2}-\d{2} (.+) \d{2}-\d{2}-\d{2}.pdf$/) { rename($name, $1); } }' *
    Hope that gives you something to get started.
  3. superscape macrumors 6502a


    Feb 12, 2008
    East Riding of Yorkshire, UK

    It looks like a crafty regular expression would be a good place to start. As the poster above mentions, you could do it in perl. Alternatively, you could do it in a cheeky bit of shell script, which would probably be the way I would attack it. You can run shell scripts from AppleScript by using "do shell script"

    Here's a Terminal command that would do it:

    find /path/to/your/folder/goes/here -type f | while read theFile; do theNewFile=`echo "$theFile" | sed "s/^[0-9]\{4\}\(-[0-9]\{2\} \)\{1,2\}//g" | sed "s/ [0-9]\{2\}-[0-9]\{2\}-[0-9]\{2\}\.pdf$/\.pdf/g"`; theFolder=`dirname "$theFile"`; mv "$theFile" "$theFolder/$theNewFile"; done
    You can probably do it a bit more elegantly than that. If you choose to do it from AppleScript then you'll have to escape some of the characters in the shell script... which will be "fun"... ;-)

Share This Page