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

    Joined:
    Sep 12, 2015
    #1
    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:
    if
    filename starts with a number
    then
    search for the delimiter " "
    endif

    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?

    gbu,
    kai-uwe
     
  2. cqexbesd macrumors regular

    Joined:
    Jun 4, 2009
    #2
    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.

    Code:
    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

    superscape

    Joined:
    Feb 12, 2008
    Location:
    East Riding of Yorkshire, UK
    #3
    Hi,

    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:

    Code:
    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