Automator/Applescript to Rename files when dropped in folder based on parent folder name

When a file is dropped in a folder ( ParentFolder/Folder/File.pdf )
I want to rename the file to ParentFolder_Folder_01.pdf
    --Get folder
    --Get ParentFolder
    --Check for next available number and use it.
    If ParentFolder_Folder_01.pdf exists, try _02
I automator, I have chosen folder action
Added 'Get selected finder items'
I have attempted to modify another sript I found here to no avail.
on run {input, parameters}
    tell application "Finder"
        set theFolder to input as string
        set theNameOfFolder to name of folder theFolder
        set theFiles to every file in folder theFolder
        set theFolders to every folder in folder theFolder
        my ProcessFiles(theNameOfFolder, theFiles)
        my ProcessFolders(theFolders)
    end tell
end run
to ProcessFolders(theFolders)
    tell application "Finder"
        repeat with thisFolder in theFolders
            set theNameOfFolder to name of thisFolder
            set theFiles to every file in thisFolder
            set theFolders to every folder in thisFolder
            my ProcessFiles(theNameOfFolder, theFiles)
            my ProcessFolders(thisFolder)
        end repeat
    end tell
end ProcessFolders
to ProcessFiles(NameOfOuterFolder, theFiles)
    tell application "Finder"
        repeat with thisFile in theFiles
            set theSuffix to my grabSuffixOfFile(name of thisFile)
            set name of thisFile to NameOfOuterFolder & "_" & theSuffix
        end repeat
    end tell
end ProcessFiles
to grabSuffixOfFile(theFile)
    set text item delimiters to "_"
    return (text item 2 of theFile)
    set text item delimiters to ""
end grabSuffixOfFile

Normally it is a bad idea to do things with items that are in the attached folder (earlier OS versions will retrigger folder actions when an item is renamed, for example), and you don't need to use a Get Selected Finder Items action since the dropped items are already passed to your workflow (also note that the input items will be a list).
It looks like you are trying to use multiple passes to add on the folder names, but you will have less of a headache if you build the base name and just deal with the number suffix.  If I understood your naming scheme correctly, the following script should do the trick - it isn't very fast, but should be OK for a few items at a time.
on run {input, parameters} -- rename input Finder items (aliases) to name of containing folders
  set divider to "_" -- the divider character between name pieces
  set output to {} -- the result to pass on to the next action
  set counter to "01" -- start suffix at one
  repeat with anItem in the input -- step through each item in the input
  set anItem to contents of anItem -- dereference
  tell application "Finder" to if class of item anItem is document file then -- don't mess with folders or applications
  set {itemParent, itemExtension} to {container, name extension} of anItem
  if itemExtension is not "" then set itemExtension to "." & itemExtension
  set grandParentName to name of container of itemParent
  set parentName to name of itemParent
  set newName to grandParentName & divider & parentName & divider & counter
  set documentNames to my getExistingNames(itemParent)
  repeat while newName is in documentNames -- increment counter suffix as needed
                                        set counter to text -2 thru -1 of ("0" & (counter + 1))
  set newName to grandParentName & divider & parentName & divider & counter
  end repeat
  set name of anItem to (newName & itemExtension)
  set end of output to anItem -- alias still refers to the same file even after renaming
  end if
  end repeat
  return the output
end run
to getExistingNames(someFolder) -- get base document names (no extensions) from a folder
  set nameList to {}
  tell application "Finder" to repeat with aFile in (get document files of someFolder)
  set {fileName, fileExtension} to {name, name extension} of aFile
  if fileExtension is not "" then set fileExtension to "." & fileExtension
  set fileName to text 1 thru -((count fileExtension) + 1) of fileName -- just the name part
  set end of nameList to fileName
  end repeat
  return nameList
end getExistingNames

Similar Messages

  • Advanced applescript to rename files

    Hi Everybody,
    I am trying to do some applescript to rename files.
    I know some tips to do that, but I try to write an advanced script with many options
    For example : A file to rename :
    "project-test.info.jpg"
    1st :
    I would like the script to find every symbols in the name(without the extension), like here : "-" or "_"
    and repace these symbols with another one like "_"
    then the new name will be :
    "project_test_info.jpg"
    2nd :
    if the file is named in a "wrong way", like :
    test.jpg
    or
    "test-info.jpg"
    or
    "project.test.jpg"
    etc
    then the script will rename in the better way :
    "project_test_information.jpg"
    (information will be data I will enter by myself)
    And many other or examples with all the possibilities to rename...
    I succeed to rename some parts of the name, but I don't find the solution to replace symbols, and how to count the number of text parts and replace the good ones...
    I dont know even if it's a good way to do like that in fact, an maybe it's possible in another way ?
    Thank you very much for your answers !

    Hi Everybody,
    I am trying to do some applescript to rename files.
    I know some tips to do that, but I try to write an advanced script with many options
    For example : A file to rename :
    "project-test.info.jpg"
    1st :
    I would like the script to find every symbols in the name(without the extension), like here : "-" or "_"
    and repace these symbols with another one like "_"
    then the new name will be :
    "project_test_info.jpg"
    2nd :
    if the file is named in a "wrong way", like :
    test.jpg
    or
    "test-info.jpg"
    or
    "project.test.jpg"
    etc
    then the script will rename in the better way :
    "project_test_information.jpg"
    (information will be data I will enter by myself)
    And many other or examples with all the possibilities to rename...
    I succeed to rename some parts of the name, but I don't find the solution to replace symbols, and how to count the number of text parts and replace the good ones...
    I dont know even if it's a good way to do like that in fact, an maybe it's possible in another way ?
    Thank you very much for your answers !

  • How can I rename files when importing?

    Is there a way to rename files when importing them? Every method I've tried retains the original file name the camera assigns (e.g. DSC_0001). I'd like the ability to rename the files automatically either with a date or event name with sequential numbering following.
    Thanks!

    First you will have to upload from the camera to a folder on the Desktop where you can batch rename them before importing into iPhoto. That's a safer workflow IMO because you can make sure the photos are safely on the hard drive before starting any other operation.
    OT

  • Any way to rename files when importing from camera with iPhoto?

    I have a naming scheme that I've used when importing photos from my camera (e.g. 2008-09-12-Event ). I can't create a custom folder (in Pictures but outside iPhoto Library) or rename things when importing with iPhoto - is that right? I can't find any advanced options to import ...
    If I want this (and don't want to use Adobe Bridge CS3), do I have to get Aperture?
    Thanks -
    Alexa
    p.s. I haven't really figured out WHERE my photos go with iPhoto? I've been editing in Photoshop Elements 6 but then have to "Save As" to replace the file - saving it doesn't do it (I think that sends it to the iPhoto library somewhere?) Eek...

    Alexa:
    You might consider this workflow:
    1 - using either Image Capture or a card reader upload the images to a folder on the desktop.
    2 - name the folder with a brief description of the shoot. I use a short date and description: 08/01/08-Dinner at Toad Hall
    3 - use a file renaming application like Resize! to batch rename the files to your specification. I use the international date (for the capture date) and a brief description: 2008-08-01-Dinner at TH-001.jpg.
    This allows for good chronological searching and sorting as well as text searching on the description. It also avoids duplicate file name issues in the future. Granted a few extra steps up front but saves me a lot of time later on.
    TIP: For insurance against the iPhoto database corruption that many users have experienced I recommend making a backup copy of the Library6.iPhoto (iPhoto.Library for iPhoto 5 and earlier) database file and keep it current. If problems crop up where iPhoto suddenly can't see any photos or thinks there are no photos in the library, replacing the working Library6.iPhoto file with the backup will often get the library back. By keeping it current I mean backup after each import and/or any serious editing or work on books, slideshows, calendars, cards, etc. That insures that if a problem pops up and you do need to replace the database file, you'll retain all those efforts. It doesn't take long to make the backup and it's good insurance.
    I've created an Automator workflow application (requires Tiger or later), iPhoto dB File Backup, that will copy the selected Library6.iPhoto file from your iPhoto Library folder to the Pictures folder, replacing any previous version of it. It's compatible with iPhoto 6 and 7 libraries and Tiger and Leopard. Just put the application in the Dock and click on it whenever you want to backup the dB file. iPhoto does not have to be closed to run the application, just idle. You can download it at Toad's Cellar. Be sure to read the Read Me pdf file.
    Note: There's now an Automator backup application for iPhoto 5 that will work with Tiger or Leopard.

  • Automator: Impossible to rename file using automator under Mac OS X Lion

    Hi,
    Before upgrade my iMac to MAC OS X Lion 10.7.2, I had service created with automator under snow leopard in order to rename my pictures file names by blocks instead of one by one. Since I'm using Lion, this one doesn't work anymore. I have completely recreate the service under Lion and the results is the same.
    You can find below my workflow that is easy. The problem is the message error in the history of automator application. The message is "impossible to rename file "file name" because this one should create conflict with existing file". I already test a lot of times with different name where I'm sure that this one doesn't exist on my Mac but all the time without success (verify also with search function under mac)
    If somebody can help me, it would be very interesting because I already tried to find answer on internet without success too.
    Thanks in advance for your help.

    the whole automator and in particular the record action was substantially rewritten in snow leopard. and the record action is slow, unreliable and you can't trouble-shoot it. it's a wonder it works at all. the only advice i can give is to use it as little as possible. if at all possible avoid it altogether. if you do need to use it try using keyboard strokes instead of the mouse movement. for example. use command+c and command+v for copying and pasting and use tabbing to choose the correct box on the page.

  • Copy new file when dropped in one folder to another

    Hi!
    I have two folders, FolderA and FolderB
    When a file is dropped in FolderA I want it to be copied to FolderB.
    FolderA will contain other items, I only want to copy new files as they are dropped in FolderA regardless of what else is in either Folder and without copying the entire contents of FolderA.
    This seems such a simple request but I cannot fathom it out.
    Any suggestions greatly received.
    Thanks
    Colin

    make the following folder action attached to folder A. (I tested it and it works).
    on adding folder items to this_folder after receiving added_items
    tell application "Finder"
    try
    duplicate added_items to folder "B" of folder "Desktop" of folder "username" of folder "Users" of startup disk
    end try
    end tell
    end adding folder items to
    In place of "username" put the name of your home directory. Also the above script works if folder B sits on the desktop. If it's somewhere else, modify the path in the above script.
    Hope this helps.

  • Renaming files when burning a data disc

    Well, with iTunes 4.x, it used to be that when you burned a data disc from iTunes on a Mac, it would rename files with characters that were invalid on other OSes (like "?"). And with iTunes 5.x - NOPE! Now I cannot copy files from my Mac over to iTunes on my PC.
    Nice job again Apple. Your QA is absolutely TOP NOTCH!

    use an older version of itunes, it works fine that way.
    Back them up as data disks, then unistall it and reinstall an older version, it will work fine

  • Automator Script to rename files with the file's Comment text?

    Hello and thank you for your time!
    Summary:
    I'd like to have an Automator Script that would copy the File's Comment info and paste it to the File's name, so I can import my sound effects into iTunes and have the proper labeling.
    Breakdown:
    I have a ton of Sound Effects that I'd like to put into iTunes, but the filenames are for example, "04. Track 04.mp3".  Not the most helpful name.
    I can search by "car crash" in the finder and find THAT file ("04. Track...")  because it's in the File's metadata in the Comment info, as "Car Crash - Chevy Camaro".
    So is there a script or a way to script Automator to copy the File's Comment info and paste it to the File's name, so I can import these into iTunes and have the proper labeling?
    Thank you for reading!
    - Ben

    This should be much faster and direct....
    Source = "C:\temp" 
    Destination "C:\newTemp"
    Set objFSO = CreateObject("Scripting.FileSystemObject")     
    Set arrFiles = objFSO.GetFolder(Source).Files  
    For Each file In arrFiles  
        If InStr(LCase(file.name), ".zip.") > 0 Then 
            arrFilename = Split(lcase(file.name), ".zip.")  
            newname = arrFilename(0) & ".zip" 
            WScript.Echo file.name & " -> " & newname  
            objFSO.CopyFile file.path, Destination & "\" & newname
        End If 
    Next 

  • Applescript to move files in a folder to the parent folder.

    I've got tens of thousands of files in folders that I'd like to be automatically moved out of the folder thier in to the parent folder.
    For example:
    Summer Vacation/img/photo.jpg
    I need all of the files in the folder img to be moved out of img and into Summer Vacation.
    Monthy Report/final/report.ppt
    I need all of the files in the folder final to be moved out of final and into Monthly Report.
    So the specifics are many and varying. A script that would work without specific file and fodler names might work better.
    Any thought on this would be greatly appreciated.

    You can use launchd to run a script daily.
    The script would move files that are older than 7 days (based on the access time) from the Downloads Folder to the Desktop (edit as needed):
    #!/bin/bash
    seven_days_ago=$(date -v -168H +%s)
    for f in ~/Downloads/*
    do
              if [ -e "$f" ] ; then
                        if [ $(stat -f %Da "$f") -lt $seven_days_ago ]; then
                                  mv "$f" ~/Desktop
                        fi
              fi
    done
    Put this script in your favorite Folder (I use ~/Library/Scripts)
    Now to trigger the script daily, place this launchd plist in ~/Library/LaunchAgents/, and edit for the location of the script, and when you want it to run (I have it at 8:24pm daily).  Reboot (or log out and back in) for the launchd to take effect.
    <?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>KeepAlive</key>
              <false/>
              <key>Label</key>
              <string>com.tonyt.MoveFiles</string>
              <key>ProgramArguments</key>
              <array>
                        <string>/Users/Tony/Library/Scripts/MoveFiles.sh</string>
              </array>
              <key>StartCalendarInterval</key>
              <dict>
                        <key>Hour</key>
                        <integer>20</integer>
                        <key>Minute</key>
                        <integer>24</integer>
              </dict>
    </dict>
    </plist>

  • HT2488 renaming subfolders based on parent folder name

    I have several hundred folders, each containing a number of subfolders.  I would like to create a workflow that will rename the subfolders so they contain the name of the parent folder.  No luck thus far...

    Many of the subfolders do contain subfolders of their own -- I want to keep those in the subfolders they're currently in, but not rename them.  In otherwords they should move with the subfolder in question with no changes.
    This is a bit murky.
    So you have
    New York
    - Images
    - History
    - Things to do
    and possibly
    Boise
    - Images
         - Nice Images <<<<<<
    - History
    - Things to do
    So how does that work out in the final set up?
    Like this
    Images
    - Nice Images <<<<<<
    - New York
    - Boise
    History
    - New York
    - Boise
    Things to do
    - New York
    - Boise
    or
    Images
    - New York
    - Boise
         - Nice Images <<<<<<
    History
    - New York
    - Boise
    Things to do
    - New York
    - Boise
    It's getting a bit evolved. Recreating the hirearcy isn't to much of a problem, moving the subfolders of the subfolders requires some thought.
    Message was edited by: Frank Caggiano - Also how much help do you need here, how much Applescript do you know? Do you just need some ideas to get going or do you need more than that?

  • AppleScript to handle the original file when I add an alias to a folder

    I'm looking for a Folder Action to solve this problem:
    When I add a file to a specific folder (the files added to this folder are always aliases), I want the original file of the alias to get his label color setted to another color.
    How can I do this?
    Jean-François

    Hello
    You may try something like the following script.
        This script can be run in three ways -
        [1] run as automator folder action; argv = {input, parameters} where input is alias list added to folder
        [2] run in editor; argv = script (self)
        [3] run as applescript folder action; argv = alias list added to folder
    on run argv
        if argv's class = list then -- [1]
            _main(argv's item 1)
        else -- [2]
            choose file of type {"com.apple.alias-file"} with multiple selections allowed
            _main(result)
        end if
    end run
    on adding folder items to d after receiving argv -- [3]
        _main(argv)
    end adding folder items to
    on _main(argv)
        script o
            property |LABEL| : 4
                0   none
                1   orange
                2   red
                3   yellow
                4   blue
                5   purple
                6   green
                7   gray
            property aa : argv
            repeat with a in my aa
                set a to a's contents
                tell application "Finder"
                    if item a's class = alias file then
                        set item a's original item's label index to |LABEL|
                    end if
                end tell
            end repeat
        end script
        run script o
    end _main
    Briefly tested under OS X 10.6.8.
    * Note that folder action can be very slow to be triggered.
    Regards,
    H

  • ITunes 12 no longer renames files when "title" field updated?

    I let iTunes do the organization of my media folder. In the past when I've added video files to my library, I use the "get info" to update the tags (title, name of show, season, etc...). iTunes would dutifully change the name of the original file in the media library folder to some formula that read the tags from the actual file - [episode] [title], for instance.
    When I "upgraded" to iTunes 12, this functionality stopped working, and iTunes doesn't rename any of the files any more. I seem to be stuck with whatever name my DVR software chose for the file. Any way to get iTunes to resume its previous behavior?

    There appears to be a bug with the way the current version processes updates to video files. You can go into Edit > Preferences > Advanced, turn Keep iTunes Media folder organized off, click OK, then turn that option back on again to resolve. Hopefully the next release will fix this but in the meantime you will need to apply the workaround each time you update something that is affected, or not worry about it.
    tt2

  • Illustrator renaming files when saving

    I am working in Illustrator CS2 on a PC. When I open a .ai file that I created, work a bit and save again, my files are being renamed. Example: My original file that was named "planning details.ai" gets renamed to "PLANNI~5.ai."
    Why is this happening? Thanks!

    What you are describing is an OS issue. Or possibly a DOS issue (Even though they say it no longer exists, ha). The first name is a long file name and the second is a short file name.
    The short file name is used if you are using an FAT formated drive. An option is enabled in windows to use short file names only. Another possiblity is a portion of your Table on the hard drive is corrupted.
    The Fat table can be changed using a utility in windows that converts FAT to NTFS or Formatting the drive, that is assuming the drive can be changed. Some drives like flash drives for a camera may be required to stay as a FAT drive for the camera to work correctly.
    The option for enabling short filenames may no longer be available. Windows use to have a place to change settings when issues come up to rule out the cause. Its possible that during Windows 98 to Windows ME it got phased out. I did not see it in Windows XP but then again quite a few options are now hidden. So if you did not change it yourself odds are you can rule out this theory.
    As far as a corrupt NTFS Table goes it might be as simple as using chkdsk.exe or as bad as formating the drive. Odds are you would notice this issue when saving any or all new documents and reading a directory (folder) may show jibbersh or the short filenames only.
    The tell tale sign of a short file name is the length of the name which is a maximum of 8 characters, plus the period, then the 3 character extention. If the long file name exceeds the limit of the short file name, a ~ character is used just before the period and the extention is trunicated to the first three characters after the period. Also the short file name can only use alphanumeric characters.
    Hopefully this helps some. I do not think there is an option in Illustrator for determining which filename type to use. As this is usually left up to the OS.
    Good luck...

  • Word 2013 COM automation fails to open file when offline

    I'm getting a weird error the I'm guessing may be related to OneDrive integration in Word 2013.
    I've got a Python script that uses COM Automation to get Word to open a .DOC/.DOCX file (the script should then paste something into the very first line, save the document, and close it).  When I'm online everything works great.  While
    using Word 2010 everything worked great, online and offline.  
    When I'm on the bus (and, therefore, offline - there's no WiFi/Clearwire/etc for my laptop) the script fails, and it fails specifically at the  line where I try to do the following:
    wordapp.Documents.Open("path_To_File\file.doc");
    The directory that contains the file is in OneDrive; it is marked as being "Available Offline".  
    My guess is that when Word 2013 is not on a network it's having trouble with the OneDrive integration.  
    I'd love any advice on either fixing this or what to look for next to better diagnose this problem.

    Hi,
    This issue more about Script, if you want more profession suggestion, please post it in TechNet Script Forum.
    http://social.technet.microsoft.com/Forums/scriptcenter/en-US/home?forum=ITCG
    The reason why we recommend posting appropriately is you will get the most qualified pool of respondents, and other partners who read the forums regularly can either share their knowledge or learn from your interaction with us. Thank you for your understanding.
    Greta Ge CHN
    TechNet Community Support

  • Automatically open files when dropped into a folder

    I have a folder which has a constant stream of images being dropped into it. Is it possible for Photoshop to automatically open recently added images of a certain folder, then save (as .psd) and close to a different location?
    It would be nice for Photoshop to do this overnight as new images are being dropped into the folder.

    As a start you could read this thread.
    http://www.ps-scripts.com/bb/viewtopic.php?t=1735&postdays=0&postorder=asc&start=0

Maybe you are looking for