Applescript create folder from filename and move file stopped working

Hi,
For a while I've used this script but after upgrade and a new machine it stopped working.
I have  Mac OS 10.8.5.
This is what I have.
Images (folder)
111111_00.jpg
111111_01.png
222222_01.jpg
222222_02.png
222222_03.gif
I'd like to be able to create a new folder for each "group of files" (new folder 111111, new folder 222222) and move the appropriate files into each of them.
The filenames are always built by 6 digits underscore and 2 digits. Can be whatever filetype. (123456_01.jpg)
I have a script that used to work just fine but now it just creates one folder and then freezes.
This is the script that doesn't work.
set chosen_folder to (choose folder)
tell (a reference to my text item delimiters) to set {old_delim, contents} to {contents, "_"}
tell application "Finder"
    try
        set file_list to files of chosen_folder
    on error
        set file_list to {}
    end try
    repeat with this_file in file_list
        set folder_name to name of this_file
        if folder_name contains "." then set folder_name to ((text items 1 thru -2 of folder_name) as string)
        set new_folder to ((chosen_folder as string) & folder_name & ":")
        try
            get new_folder as alias
        on error
            make new folder at chosen_folder with properties {name:folder_name}
        end try
        move this_file to folder new_folder without replacing
    end repeat
end tell
set my text item delimiters to old_delim
I know that there are many who can do this easy as pie, but if you can find it in your hearts to help me it would be much appreciated.
K

function createFolder(file) {
  var parentFolder = file.parent;
  var saveFolder = new Folder( parentFolder + '/' + file.name.substring( 0, 8 ) );
  if( !saveFolder.exists ) saveFolder.create();
  var saveFile = new File( saveFolder + '/' + file.name);
  if( file.copy( saveFile ) ) file.remove();
function main() {
   var folder = new Folder("~/Desktop/images");
   var files = folder.getFiles();
   for (var i = 0; i < files.length; i++) {
     var f = files[i];
     if (f instanceof File) {
      createFolder(f);
main();
Something like that should work.

Similar Messages

  • Automator: Create folder from filename

    I am trying to use Automator to query a file in a foldr, then create a folder based off of the filename, then move the file into the newly created folder. I am not as savvy as I thought that I was when it comes to Automator. Even thinking that Automator might not be the correct tool for the job. Each file has a different name or this would be a lot easier. Any help would be greatly appreciated.

    You can use a Run AppleScript action to do the work, and feed items to it by using a service workflow, an Ask for Finder Items action, etc - for example:
    1) Service receives selected files or folders in Finder
    2) Get Folder Contents
    3) Run AppleScript
    on run {input, parameters} -- create folders from file names and move
      set output to {} -- this will be a list of the moved files
      repeat with anItem in the input -- step through each item in the input
        set {theContainer, theName, theExtension} to (getTheNames from anItem)
        try
          set destination to (makeNewFolder for theName at theContainer)
          tell application "Finder"
            move anItem to destination
            set the end of the output to the result as alias -- success
          end tell
        on error errorMessage -- duplicate name, permissions, etc
          log errorMessage
          # handle errors if desired - just skip for now
        end try
      end repeat
      return the output -- pass on the results to following actions
    end run
    to getTheNames from someItem -- get a container, name, and extension from a file item
      tell application "System Events" to tell disk item (someItem as text)
        set theContainer to the path of the container
        set {theName, theExtension} to {name, name extension}
      end tell
      if theExtension is not "" then
        set theName to text 1 thru -((count theExtension) + 2) of theName -- just the name part
        set theExtension to "." & theExtension
      end if
      return {theContainer, theName, theExtension}
    end getTheNames
    to makeNewFolder for theChild at theParent -- make a new child folder at the parent location if it doesn't already exist
      set theParent to theParent as text
      if theParent begins with "/" then set theParent to theParent as POSIX file as text
      try
        return (theParent & theChild) as alias
      on error errorMessage -- no folder
        log errorMessage
        tell application "Finder" to make new folder at theParent with properties {name:theChild}
        return the result as alias
      end try
    end makeNewFolder
    4) other actions as desired

  • Read character 3+4 from filename and move to other position

    Hello,
    I need a javascript to read my filename (I have the one for the full filename) and especially the 3rd and 4th position of the filename.
    The characters on position 3 and 4 must be moved to the position just before the extension.
    Example:
    4PEN12345.pdf (old name) should be 4P12345_EN.pdf
    Now I have the following script to extract all pages in an existing pdf file to separate pages with all the same suffix before the extension
    /* Extract Pages to Folder */
        var re = /.*\/|\.pdf$/ig;
        var filename = this.path.replace(re,"");
            for ( var i = 0;  i < this.numPages; i++ )
            this.extractPages
                nStart: i,
                nEnd: i,
                cPath : filename + "_page_" + (i+1) + "_EN.pdf"
    Can anybody help me to set me on the right direction?

    Now I have the file 4PBG12345-1.pdf (7 pages included in the pdf).
    Your script as I filled in:
    /* Extract Pages to Folder */
        var re = /.*\/|\.pdf$/ig;
        var filePath = this.path.replace(this.documentFileName, "");
        var oldFileName = this.documentFileName;
        var suffix = oldFileName.substring(2,4);
        var newFileName = oldFileName.substring(0,2) + oldFileName.substring(4).replace(".pdf", "_"+suffix+".pdf");
        var newFilePath = filePath + newFileName;
            for ( var i = 0;  i < this.numPages; i++ )
            this.extractPages
                nStart: i,
                nEnd: i,
                cPath : newFilePath
    Result:
    1 file ==> 4P12345-1_BG.pdf (7 pages included in the pdf)
    Of course, because the syntax for extracting and adding automatic pages is not filled in. So, that was my question, how must I nest to add the right:
    Filepath+oldfilenamesubstring(0,2)+oldfilenamesubstring(4)+_page_i++_+suffix+.pdf in the extract section
    So, my example must result in 7 pdf's:
    4P12345-1_page_1_BG.pdf (with content of page 1)
    4P12345-1_page_2_BG.pdf (with content of page 2)
    4P12345-1_page_3_BG.pdf (with content of page 3)
    4P12345-1_page_4_BG.pdf (with content of page 4)
    4P12345-1_page_5_BG.pdf (with content of page 5)
    4P12345-1_page_6_BG.pdf (with content of page 6)
    4P12345-1_page_7_BG.pdf (with content of page 7)

  • Create folder from filename

    Hi
    I need a script that move files to a folder with the same name as the first 8 characters of the file name, that has to be moved. If the folder doesn't exist, it has to be created. I'm new in Javascript! Can anybody help me??
    thanx

    function createFolder(file) {
      var parentFolder = file.parent;
      var saveFolder = new Folder( parentFolder + '/' + file.name.substring( 0, 8 ) );
      if( !saveFolder.exists ) saveFolder.create();
      var saveFile = new File( saveFolder + '/' + file.name);
      if( file.copy( saveFile ) ) file.remove();
    function main() {
       var folder = new Folder("~/Desktop/images");
       var files = folder.getFiles();
       for (var i = 0; i < files.length; i++) {
         var f = files[i];
         if (f instanceof File) {
          createFolder(f);
    main();
    Something like that should work.

  • MOV Files stop working

    Hello,
    I'm working on some MOV files in CS4 and they will randomly stop working; my image is lost.  Sometimes it does this when exporting as well; it will, to my suprise, pick clips and make them a blank screen.  Please help!

    Read Bill Hunt on a file type as WRAPPER
    http://forums.adobe.com/thread/440037?tstart=0
    What is a CODEC... a Primer http://forums.adobe.com/thread/546811?tstart=0
    What CODEC is INSIDE that file? http://forums.adobe.com/thread/440037?tstart=0
    Report back with the codec details of your file, use the programs below
    For PC http://www.headbands.com/gspot/ or http://mediainfo.sourceforge.net/en
    For Mac http://mediainfo.massanti.com/
    Once you know exactly what it is you are editing, report back with that information... and your project setting, and if there is a red line above the video in the timeline, which indicates a mismatch between video and project
    More information needed for someone to help http://forums.adobe.com/thread/416679
    Some is general about your computer and OS, some is specific to video editing
    Build a Configuration file http://www.piriform.com/speccy
    Brand/Model Computer (or Brand/Model Motherboard if self-built)
    How much system memory you have installed, such as 2Gig or ???
    Operating System version, such as Win7 64bit Pro... or whatevevr
    -including your security settings, such as are YOU the Administrator
    -and have you tried to RIGHT click the program Icon and then select
    -the Run as Administrator option (for Windows, not sure about Mac)
    Your Firewall settings and brand of anti-virus are you running
    Brand/Model graphics card, sush as ATI "xxxx" or nVidia "xxxx"
    -or the brand/model graphics chip if on the motherboard
    -and the exact driver version for the above graphics card/chip
    -and how much video memory you have on your graphics card
    Brand/Model sound card, or sound "chip" name on Motherboard
    -and the exact driver version for the above sound card/chip
    Size(s) and configuration of your hard drive(s)... example below
    -and how much FREE space is available on each drive (in Windows
    -you RIGHT click the drive letter while using Windows Explorer
    -and then select the Properties option to see used/free space)
    Windows Indexing is BAD http://forums.adobe.com/thread/676303
    While in Properties, be sure you have drive indexing set OFF
    -for the drive, and for all directories, to improve performance
    Some/Much of the above are available by going to the Windows
    Control Panel and then the Hardware option (Win7 option name)
    OR Control Panel--System--Hardware Tab--Device Manager for WinXP
    And the EXACT type and size of file that is causing you problems
    -for pictures, that includes the camera used and the pixel dimensions
    Plus Video-Specific Information http://forums.adobe.com/thread/459220?tstart=0

  • [Solved] Moved from location and internet connection stopped working.

    Hello everyone, this is my first post in the forums and first time using arch so please bear with me. I recently bought an Asus UX51, formatted it and installed arch linux with the help of the beginner's guide. After overcoming several problems (preinstalled raid, nvidia optimus to name a few) I managed to get it running, installed a DE and was using wireless connection just fine with
    # ip link set wlp3s0 up
    # wifi-menu wlp3s0
    Everything was going fine until I came for a holyday's week to my parents house and tried to connect to their wireless network to no avail. I have WAP in my house, same do they in their house (in which I'm right now).
    I have been trying the past 2 days with netctl, and even the manual method described in the wiki , googled, etc. I'm already out of ideas so I decided it was time to ask for help. If it's of any use, wifi-menu scans the network properly, and # netctl status wlp3s0-interface_name returns this:
    Also read somewhere in the forums to try # journalctl -b , this is what I get on the last page:
    When I try #ping, I get the following after having to wait around 15 secs :
    ~$ ping google.com
    ping: unknown host google.com
    I even tried booting from an USB with an arch iso, just to try getting a wired connection, mount my arch installation and download some other network manager just to see if I got any luck, but not even that worked (in my house, just by connecting the cable before booting I would automatically have internet access when booting with the iso, but it didn't work here...).
    Any help would greatly be appreciated.
    Last edited by contiver (2013-08-01 18:06:48)

    I got it running !
    Just followed the manual guide once more, but managed to bypass some problem I had the first time I tried (you could say I was a bit lost by the command in the wiki but managed to understand it a bit more this time)
    I believe the setup my parents have here is pretty messed up, other people get similar problems from time to time with the network, but I don't really understand much to mess with it so I'd rather leave it like it is.
    In case it's of any use to anybody I'll leave here how everything was left in the end in my laptop.
    Used:
    wpa_passphrase foobarssid foobarpassword
    to generate:
    network={
    ssid="foobarssid"
    #psk="foobarspassword"
    psk=f5d1c49e15e679bebe385c37648d4141bc5c9297796a8a185d7bc5ac62f954e3
    I copy pasted that on my /etc/wpa_supplicant.conf ,which had a line at the start which seems was a leftover from the time I tried before (when I tried using wpa_supplicant it failed and complained about it in the error msg).
    After that I used
    wpa_supplicant -B -iwlp3s0 -c/etc/wpa_supplicant.conf
    After that I used
    dhcpcd -A wlp3s0
    That failed because it said that there already was a dhcpcd process running, I killed it, tried again and it all went fine. Tried ping and kept answering "unknown host". Tried rebooting and that's when # ping google.com  started to behave like it should. Tried browsing a bit and no problems whatsoever.
    Thanks a lot for the help!

  • User sip folder have many .cache files with 4kb and the folder is becoming full and Lync Client stops working

    User sip folder have manu Mailitem&username&.cache files until folder is full and Lync client stops working.

    Hi,
    You can try to change the Lync Profile name. After you do it, Lync will create a new Profile. The Lync Profile path is following:
    %UserProfile%\AppData\Local\Microsoft\Office\15.0\Lync
    If the issue persists, please repair Office 2013 and then test again.
    Best Regards,
    Eason Huang  
    Eason Huang
    TechNet Community Support

  • Using Automator and Applescript to search and move files to flash drive

    I've used applescript and automator to do simple tasks like watch folders and move files and rename files, but that is about the extent. I am wondering if it is possible to set up a automator service or app that will do several things.
    When a flash drive is plugged it, it will ask for a file to be searched for, then it will search a predetermined directory for files with the word or number in them and then it will copy the found files to the mounted flash drive.
    Any help would be greatly appriciated!
    Thanks!

    As a start, you can use launchd to run a script when a volume is mounted:
    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
    <plist version="1.0">
    <dict>
              <key>Label</key>
              <string>com.tonyt.LaunchOnVolMount</string>
              <key>ProgramArguments</key>
              <array>
                        <string>LaunchOnVolMount.sh</string>
              </array>
              <key>QueueDirectories</key>
              <array/>
              <key>StartOnMount</key>
              <true/>
              <key>WatchPaths</key>
              <array/>
    </dict>
    </plist>
    You can then have the LaunchOnVolMount.sh script perform the tasks you need.
    You can incorporate Applescript within the Bash script with osascript:
    #!/bin/bash
    answer=$( osascript -e 'tell app "System Events" to display dialog "What file do you want to search for?" default answer "" ' )
    echo $answer
    I beleive that you can also call an Applescript from launchd

  • I want to transfer my photo and movie files from my iPhone 4S to my mac.

    I have posted this question before without any success and was hoping by reposting it may promt a solution to my problem.
    I want to transfer my photo and movie files from my iPhone to my Mac OS X (10.5.8).
    But I don't want to use Cloud or iTunes.
    Is there a way to connect my iPhone 4S to my Mac directly,
    say ... via a program or such on my MAC, to drag and drop the photos and Movie files,
    directly into a folder. ??????????
    Reason want to connect iPone to MAC or MAC to iPhone is ....
    I have no DATA on my iPhone Mobile plan at moment.
    So Photosync app is no good, as I can't download the app to my iPhone.
    I can download a Photosync to my MAC ...
    but with the Photosync app you can only send data.
    Thanks in advance for any help.

    Sorry I should of mentioned ....
    Reason want to connect iPone to MAC or MAC to iPhone is ....
    I have no DATA on my iPhone plan at moment.
    So Photosync app is no good, as I can't download the app to my iPhone.
    I can download a Photosync to my MAC ...
    but with the Photosync app you can only send data  (so needs to be on the  iPhone).

  • Bridge CC freezes when downloading from CF Card .MOV files

    I have had a consistant problem since using Bridge CC.  I insert a CF Card to the ready and Bridge CC downloader automatically comes up.  The CF Card often contains JPG, CR2 and .MOV files.  No conversion or other edits are occuring accept for name change.and copyright meta data.  When the download comes to the Canon  5D Mii .MOV file it freezes and wont proceed.  I in fact have to pull up the Task Manager and stop the application to close it.  I am able to use Explorer to browse and down load all the movie flies, just not through Bridge CC - Any ideas?

    The same problem is happening to me when trying to access a shared/network drive...
    You mean trying to get .mov files from a network?? Otherwise try starting a new thread for this problem. Also be aware that Adobe officially does not support use for Bridge over a network due to the many set ups that are possible. Some get it to work with great care and understanding, others don't succeed.
    Bridge also by default has user based cache libraries and you also should have the correct permissions for the things you try to access.

  • Create Application from Database and Air

    I have tried several time to use the create application from
    database for an air app build in flex. I do the same steps and the
    only difference is that I click the create button as air not web.
    It does not seem to work. Does the create application from database
    command (referencing php mysql) work with Air???
    Thanks

    Hi Dave,
    Would you please file a bug with all the necessary details
    regarding this issue? The bug base is found at:
    http://bugs.adobe.com/jira.
    We’ll look into this. Thank you for letting us know!
    Lacra

  • Missing user folder from Workspace and FR studio

    Hi All,
    Recently we upgraded the workspace and applications... Initially there were all the folders, but i noticed that user folder from workspace and FR studio was missing... If anyone have come across this issue please let me know how to solve it.
    Awaiting for response, Thanks in advance

    Just to make sure I understand. When you double click the hard drive icon either in the sidebar or on your desktop (if you have it shown there) there is no users folder shown? If that is the case then it must somehow have become invisible. If there was in actuality no user folder at all your Mac would not boot.
    If that is the case then you may have to use the terminal to get it back. I can't help you with that though, sorry. Another possibility is that there is some sort of corruption in a cache file. You could use a tool such as YASU or others to do a light cache cleaning which may solve the problem.

  • WPA8.1 Feature to save and move files between folders and OneDrive Folders

    Hi,
    I would like to suggest to dev team a new feature to Adobe Reader on Windows Phone.
    Today I was done a uggly workarround to save one PDF file on a OneDrive folder to send to my classmates. So I would like a feature to save and move files between folders on SD cards and OneDrive to keep my phone organized.
    thank you for your time.

    Here:
    property aFolder : "a"
    property bFolder : "b"
    property cFolder : "c"
    property dFolder : "d"
    property eFolder : "e"
    tell application "Finder"
    try
    set theLocation to the selection as alias
    on error
    set theLocation to (folder of the front window as alias)
    end try
    if not (exists folder aFolder of theLocation) then make new folder at theLocation with properties {name:aFolder}
    if not (exists folder bFolder of theLocation) then make new folder at theLocation with properties {name:bFolder}
    if not (exists folder cFolder of theLocation) then make new folder at theLocation with properties {name:cFolder}
    if not (exists folder dFolder of theLocation) then make new folder at theLocation with properties {name:dFolder} 
    if not (exists folder eFolder of theLocation) then make new folder at theLocation with properties {name:eFolder}
    set this_list to every file of theLocation
    repeat with i in this_list
    if (name of i) begins with "a" then
    move i to folder "a" of theLocation
    else if (name of i) begins with "b" then
    move i to folder "b" of theLocation
    else if (name of i) begins with "c" then
    move i to folder "c" of theLocation
    else if (name of i) begins with "d" then
    move i to folder "d" of theLocation
    else if (name of i) begins with "e" then
    move i to folder "e" of theLocation
    end if
    set name of (the result) to items 3 thru -1 of (get name of (the result)) as string
    end repeat
    end tell
    (98558)

  • When deleting a user created folder from On My Mac in Mac Mail the sent messages that are part of conversations that reside there are not deleted, only the received mail gets deleted.

    When deleting a user created folder from On My Mac in Mac Mail the sent messages that are part of conversations that reside there are not deleted, only the received mail gets deleted. Any way for both the received and sent mail that resides there to be deleted?
    I create a lot of project folders where i keep all my conversations regarding the project. Once the project is finished i would like to just delete the folder and get rid of all the emails associated with it but when i delete the folder i've noticed that only received messages are deleted. Now I am stuck trying to sort through my sent folder for messages that were returned there after the conversations was supposedly deleted.

    Mail/Preferences/Viewing - un-check include related messages, delete the folder, then go back and reset yo include.

  • Hi, I would like to copy my photos (from iphoto) and movies (from i movie) from my Mac book air to my imac in which I also have iphoto and imovie with photos and movies. My goal is to have a unique source in my imac for my photos and movies. Thanks .

    Hi,
    I would like to copy my photos (from iphoto) and movies (from i movie) from my Mac book air to my imac in which I also have iphoto and imovie with photos and movies.
    My goal is to have a unique source of photos and movies in my imac.
    Thanks !
    Nicolas

    As  to iPhoto
    Connect the two Macs together (network, firewire target mode, etc)  or use an external hard drive formatted Mac OS extended (journaled) and drag the iPhoto library intact as a single entity from the old Mac to the pictures folder of the new Mac - launch iPhoto on the new mac and it will open the library and convert it as needed and you will be ready move forward.
    For iMovie support please post in the iMovie forum
    LN

Maybe you are looking for