Coping folder contents and sub folders

So, I'm working on a little practice folder sync project (fun with my mac)...
...and I'v gotten hung up a bit because my little copying app doesn't seem to count folders and sub folders (which I suppose makes sense).
My initial idea was to take just the date of modification and compare it to the last date that the app was run, inorder to only copy changed files. But this seems problematic on a few levels, so...
So, my two part question is:
1. Is there a simple command to copy folder contents and sub-folder contents, or do I need to tell the script to do each sub-folder individually?
2. I imagine that a better way to manage which files/folders need to be updated is to create a file with a list of the contents, and dates of modification, and compare the new folder list and the old folder list to each-other... ok.. so, um. yeah. that sounds tricky.

>1. Is there a simple command to copy folder contents and sub-folder contents, or do I need to tell the script to do each sub-folder individually?
There are two common solutions to this.
The first is to use the Finder's 'entire contents of...' command to get a list of everything in the folder, including sub-folders, the second is to make your script recursive - that is, it calls itself several times over.
In the first case it's as simple as:
tell application "Finder"
set allItems to entire contents of folder "path:to:source:folder:"
-- rest of code goes here
end tell
This can have problems, though, especially on very large directories since the Finder is not very efficient at building a list of hundreds or thousands of files.
The recursive path is a little trickier, but you write a handler to process a folder then repeatedly call that handler, like:
<pre class=command>on run
set sourceFolder to (choose folder)
processAFolder(sourceFolder)
end run
on processAFolder(theFolder)
tell application "Finder"
set allItems to items of folder theFolder as alias list
repeat with eachItem in allItems
if class of eachItem is folder then -- we have a subfolder
processAFolder (eachItem)
else
-- code here to compare the file and back it up
end if
end repeat
end tell
end processAFolder</pre>
So here you walk through the folder, each time you find a new folder, you walk through that until you're done. The code takes care of keeping track of where you are in the folder hierarchy.
>2. I imagine that a better way to manage which files/folders need to be updated is to create a file with a list of the contents, and dates of modification, and compare the new folder list and the old folder list to each-other... ok.. so, um. yeah. that sounds tricky.
There's no need to keep a file. Assuming you have two folders you can just walk through one of them checking to see if each item exists in the other, then copy the newer file to the other directory, like:
<pre class=command>on processAFile(fileName, sourceDir, destDir)
tell application "Finder"
-- check if the files exist
set sourceFileExists to (file fileName of folder sourceDir exists)
set destFileExists to (file fileName of folder destDir exists)
-- now comes the logic
if sourceFileExists and not destFileExsits then
duplicate file fileName of folder sourceDir to folder destDir
else if destFileExists and not sourceFileExists then
-- assuming you want a two-way synch
duplicate file fileName of folder destDir to folder sourceDir
else -- both files exist, so check mod dates
if (modification date of file fileName of folder sourceDir) > (modification date of file fileName of folder destDir) then
duplicate file fileName of folder sourceDir to folder destDir
else if (modification date of file fileName of folder destDir) > (modification date of file fileName of folder sourceDir) then
duplicate file fileName of folder sourceDir to folder destDir
end if
end if
end tell
end processAFile</pre>
If you're not planning a two-way synch an even simpler option is to just keep track of the last time the synch was run. Then all you need to do on subsequent runs is ask the Finder for 'every file of folder sourceFolder whose modification date is greater than lastRunDate'.

Similar Messages

  • Jsp code (js code) to display(tree) the files and sub folders in a folder

    Hi all
    plz can any one send me the source in jsp or js to display in tree structure for files and sub folders in a folder.

    There are dozens of Javascript tree widgets available on the Internet. Some are free. Some are good. Google will find them for you.
    (The only relevance of JSP to your question is that yes, you can generate HTML that uses one of those Javascript tree widgets.)

  • I was re-naming a folder with many sub folders suddenly Thunderbird did not respond and the folder and sub folders I was re-naming disappeared.

    I was re-naming a folder with many sub folders attached, suddenly, Thunderbird did not respond and the folder I was re-naming disappeared along with all the sub folders attached to it. How can I get them back? I am not a computer savvy person. Any help would be greatly appreciated.
    Thank you.
    [email protected]

    Turned out that my anti-virus was doing a scheduled scan and had found a virus in an email attachment in my deleted items folder, thus nothing being able to do during the scan.

  • Deleting Files and (sub)folders - how to

    Hi,
    Easy question. Easy there a vbscript to delete all files and (sub)folders, empty or not. Important, here is that the parent folder must NOT be deleted, only it´s contents. (important: this folder is located on a mapped share \\servername\foldername\)
    please help

    Hi,
    ' Delete All Subfolders and Files in a Folder
    Const DeleteReadOnly = TRUE
    Set objFSO = CreateObject("Scripting.FileSystemObject")
    objFSO.DeleteFile("C:\FSO\*"), DeleteReadOnly
    objFSO.DeleteFolder("C:\FSO\*"),DeleteReadOnly
    Save the above code in test file with .vbs file extension. modify "C:\FSO" to your folder.
    Disclaimer: This posting is provided AS-IS with no warranties or guarantees and confers no rights. Please remember to click “Mark as Answer” on the post that helps you, and to click “Unmark as Answer” if a marked post does not actually
    answer your question. This can be beneficial to other community members reading the thread.

  • Importing existing folders and sub folders of photos into photoshop organiser 9

    I have over 10,000 photos nicely organised in folders and sub folders in Bridge CS3 and want to migrate over to photoshop elements and use their organiser so I have everything in one place. However, when I try to import the photos, it brings them in as individual photos and not in their folders. It seems like I need to recreate a load of albums and then drag and drop the photos into them. I don't have time to recreate hundreds of album names to replicate my system as it is. Is there any way round this or should I be looking at a different system altogether?
    Thank you for any advice on this.

    ... should I be looking at a different system altogether?
    If your entire organizational goals are to continue to use your "nicely organised" folders, then why bother with the PSE Organizer in the first place? You have extra work (must import the photos) and more limitations (must do all photo management inside of the PSE Organizer), and its hard to see any benefit from using the PSE Organizer. You won't achieve any "better organization" than what you have now.
    If your goals are to use PSE tools to organize (tags, captions notes), in addition to (or as a replacement for) your folder organization, then the PSE Organizer can be very useful.

  • Elements 10 and Sub-folders

    I'm running PSE 10 on an iMac (OSX 10.6.8).  When I try to save a file under SAVE AS, when I click on WHERE the dialog won't let me select a sub-folder.  For example, if I have a folder named PHOTOS and have sub-folders named TRAVEL, PEOPLE, and SPORTS the only folder that shows is PHOTOS.  In Elements 7 when you click on a folder that has sub-folders, that sub-folders are displayed.
    What am I doing wrong?
    Thanks.
    Ken

      If you go to the External Editing tab in Lightroom preferences you should see PSE10 shown as the first or second editor.
    I normally send my raw files into PSE as a PSD file or tiff with the Lightroom settings.
    The sequence is:
    1) Select image in Lightroom Library and press Cmd+E
    2) Edit in Elements and press Cmdl+S to save
    3) Press Cmd+W to close file in Elements and update Lightroom.
    If you want to save in a different folder or sub-folder you need to use the export button in the Ligtroom Library.
      

  • How To Add Folders and Sub Folders

    I am brand new (1 week) to my new Mac (iMac). In my Windows-based PC I used to have, for example, a folder named PHOTOS followed by sub folders designating certain categories that work for me, such as, "Family", "Vacations" etc, and I would make sure that all my uploads from my camers went to the appropriate folder.
    I would like to accomplish the same thing in my Mac, but have no idea how to go about it. I do not even know how to create such folders and sub folders.
    Is someone out there who can help, please?

    pstoll
    In the Finder: File -> New Folder creates a new Folder. To nest a folder inside another one then simply drag the second one to the first.
    But if you're trying to organise your photos, there's a much better way to do that on your Mac. Check out iPhoto It's a photo manager that's integrated throughout the Operating System. It's much, much more flexible than a bunch of folders in the Finder. You can keyword your pics, populate Smart Albums automatically, rate and edit your pics, all via iPhoto.
    You can find out more here:
    http://www.apple.com/ilife/iphoto/
    there are some tutorials here
    http://www.apple.com/ilife/tutorials/#iphoto
    and a good forum here:
    http://discussions.apple.com/category.jspa?categoryID=143
    My best advice is to explore the app by dragging in maybe 100 pics and testing things out, gettting the hang of it. It's miles better than a folder hierarchy.
    Regards
    TD

  • Working with Folders and Sub-Folders

    I'm updating this big site, and its pages are organized into
    folders. I've only ever organized my images and .pdf files with
    folders not my html files but all my prior sites have never had so
    many files as this one. It’s starting to drive me crazy
    though because pages in folders aren't connecting to scripts in the
    scripts folder, menus aren't working right because of it and I'm
    not sure what I can do to fix it.
    My question is if images are showing up in these sub-pages,
    the linked css is being applied in these sub-pages why are the
    scripts not working in the sub-pages? For example, all the top
    level pages easily connect to the rotating JavaScript banner, but
    as soon as you go into a sub-folder page the banner disappears. All
    these files are being updated via templates so any changes I'm
    doing is affecting all the pages the same. That’s why
    it’s confusing me why an image would connect the same but a
    script wouldn't. Don't they search for their links root down or
    does it search the folder its in down? How can you get templates to
    work under such conditions where files are both in the root and in
    folders and sub-folders?
    Site reference is:
    http://golfforkids.net/focus/index.html
    Please note that this is a temporary domain for testing. The
    top menu will pop up a window saying that it needs to be
    registered. They are, just not to that domain and I don't have
    access to the native domain. Sorry for the inconvenience!
    Thank you for any clarification!!!

    ''"Are you subscribed to those subfolders?
    File (Alt-F) - Subscribe"''
    Please see #2 in original post:
    ''"2) Trying to Subscribe to folders only shows Inbox, not sub-folders for Inbox."''
    Attached is an image illustrating this (this screenshot was taken after forcing Thunderbird to show Inbox folders as described in #3 of OP)
    {In OP I was unable to attach images}

  • Unlocking All Folders and Sub Folders When Sharing

    Is there a way to share files and unlock them automatically. I Have many hundreads of excel and word docs in folders and sub folders.
    After a day scratching my head trying to work out why I could not save them on the shared computer I realized that I needed to unlock the folder.
    Excel does not have in its preferences anything that suggest this....it gets old real quick opening each file and then typing my computer password for each folder/ file etc....truly hope this can be done.
    Thanks in advance!

    Anyone???

  • How to create folders and sub folders in numbers on my mac book pro?, how to create folders and sub folders in numbers on my mac book pro?

    I am new to Mac and numbers how do I create folders and sub folders on my mac book pro ? I have created folders on my ipad3 but I cant seem to make a sub folder ?
    Can any one help ?
    Thanks in advance!

    To create a folder either select New Folder from the Finder's File menu or the keyboard equivalend command-shift-N.  Select that folder and do the same. Viola!  You have a folder inside a folder.

  • I am struggling! Help! I need to move 3500 pics-in TIFF format in 175 folders and sub folders from my old PSE6, Windows XP to my new PSE13, Windows8.1. I have the PSE6 backed up on an external hard drive. What is the safe way to do this? Can anyone at Ado

    I am struggling! Help! I need to move 3500 pics-in TIFF format in 175 folders and sub folders from my old PSE6, Windows XP to my new PSE13, Windows8.1. I have the PSE6 backed up on an external hard drive. What is the safe way to do this? Can anyone at Adobe help me? Please?

    Use the Organizer backup & restore method, starting the restore from the TLY file. Probably best to use a custom location as the XP file structure will be different. See this link for further help:
    http://helpx.adobe.com/photoshop-elements/kb/backup-restore-move-catalog-photoshop.html

  • Can I arrange my bookmarks so that the folders and sub-folders are at the top of the list like in Explorer?

    I transferred all of my "Favorites" from Explorer. I have a lot of folders and sub-folders and I would like these to be listed at the top (as in Explorer) with individual bookmarks below. Right now the folders and individual bookmarks are mixed together.

    http://kb.mozillazine.org/Sorting_and_rearranging_bookmarks_-_Firefox
    If you '''Sort by Name''' in the Bookmarks Sidebar, that is how Firefox sorts bookmarks. If you have any '''''Separators''''', the Sort will stop there and you'll have to Sort from there down separately.

  • HT201250 When restoring Time Machine after a failure, does it also restore the files to the same order, for example - within iPhoto I have pics/ videos in folders and sub folders organised as family/events etc - will it go back to this exact order after a

    When restoring Time Machine after a failure, does it also restore the files to the same order, for example - within iPhoto I have pics/ videos in folders and sub folders organised as family/events etc - will it go back to this exact order after a restore?

    Hi Stavros0203,
    When restoring your entire system from a Time Machine backup, it is restored to the state it was when that backup was made. See this article for reference -
    OS X Yosemite: Recover your entire system
    Thanks for using Apple Support Communities.
    Best,
    Brett L

  • Urgent ! How to Zip Folder Contents including files and sub folders.

    Hi, i need an urgent help from you regarding zipping the contents of any folder/directory including its sub folders and files to a .zip file. Please provide a code for ot or help me out. It is really very urgent.
    Thanx Waiting....

    This class can add a string or file to a ZIP. Maybe you can adapt it to do a directory and all its subfolders and files recursively:
    package demo;
    import java.io.BufferedReader;
    import java.io.ByteArrayInputStream;
    import java.io.ByteArrayOutputStream;
    import java.io.File;
    import java.io.FileReader;
    import java.io.IOException;
    import java.util.zip.GZIPInputStream;
    import java.util.zip.GZIPOutputStream;
    import java.util.zip.ZipException;
    * Demo for using the Zip facilities to compress data
    public class ZipDemo
        /** Default buffer size */
        private static final int DEFAULT_BUFFER_SIZE = 4096;
         * Compress a string
         * @param uncompressed string
         * @return byte array containing compressed data
         * @throws IOException if the deflation fails
        public static final byte [] compress(final String uncompressed) throws IOException
            ByteArrayOutputStream baos  = new ByteArrayOutputStream();
            GZIPOutputStream zos        = new GZIPOutputStream(baos);
            byte [] uncompressedBytes   = uncompressed.getBytes();
            zos.write(uncompressedBytes, 0, uncompressedBytes.length);
            zos.close();
            return baos.toByteArray();
         * Uncompress a previously compressed string;
         * this method is the inverse of the compress method.
         * @param byte array containing compressed data
         * @return uncompressed string
         * @throws IOException if the inflation fails
        public static final String uncompress(final byte [] compressed) throws IOException
            String uncompressed = "";
            try
                ByteArrayInputStream bais   = new ByteArrayInputStream(compressed);
                GZIPInputStream zis         = new GZIPInputStream(bais);
                ByteArrayOutputStream baos  = new ByteArrayOutputStream();
                int numBytesRead            = 0;
                byte [] tempBytes           = new byte[DEFAULT_BUFFER_SIZE];
                while ((numBytesRead = zis.read(tempBytes, 0, tempBytes.length)) != -1)
                    baos.write(tempBytes, 0, numBytesRead);
                uncompressed = new String(baos.toByteArray());
            catch (ZipException e)
                e.printStackTrace(System.err);
            return uncompressed;
         * Uncompress a previously compressed string;
         * this method is the inverse of the compress method.
         * Implemented in terms of the byte array version.
         * @param string containing compressed data
         * @return uncompressed string
         * @throws IOException if the inflation fails
        public static final String uncompress(final String compressed) throws IOException
            return ZipDemo.uncompress(compressed.getBytes());
         * Main driver class for ZipDemo
         * @param command line arguments - either string or file name to compress
        public static void main(String [] args)
            try
                for (int i = 0; i < args.length; ++i)
                    String uncompressed = "";
                    File f              = new File(args);
    if (f.exists())
    BufferedReader br = new BufferedReader(new FileReader(f));
    String line = "";
    StringBuffer buffer = new StringBuffer();
    while ((line = br.readLine()) != null)
    buffer.append(line);
    br.close();
    uncompressed = buffer.toString();
    else
    uncompressed = args[i];
    System.out.println("length before compression: " + uncompressed.length());
    byte [] compressed = ZipDemo.compress(uncompressed);
    System.out.println("length after compression : " + compressed.length);
    String compressedAsString = new String(compressed);
    System.out.println("length of compressed str : " + compressedAsString.length());
    byte [] bytesFromCompressedAsString = compressedAsString.getBytes();
    boolean isTheSameAs = bytesFromCompressedAsString.equals(compressed);
    System.out.println("compressed bytes are " + (isTheSameAs ? "" : "not ") + "the same as from String");
    System.out.println("length of bytesFrom...: " + bytesFromCompressedAsString.length);
    String restored = ZipDemo.uncompress(compressed);
    System.out.println("length after decompress : " + restored.length());
    isTheSameAs = restored.equals(uncompressed);
    System.out.println("original is " + (isTheSameAs ? "" : "not ") + "the same as the restored");
    String restoredFromString = ZipDemo.uncompress(compressedAsString);
    isTheSameAs = restoredFromString.equals(uncompressed);
    System.out.println("original is " + (isTheSameAs ? "" : "not ") + "the same as the restored from string");
    catch (Exception e)
    e.printStackTrace(System.err);
    MOD

  • How to monitor contents of sub-folders in a Folder Action?

    Hello. I am wondering how I might read a folder's contentModDate within Terminal, i.e. from the command line and/or within a Folder Action.
    This is the situation: I am running Periscope Pro (PP) for motion-detected videos, which by default, places them within the user's ~/Movies/com.zipzapmac.Periscope-Pro folder. Within that folder, PP creates a folder with it's name based upon (a) machine name and (b) primary MAC address. For example, we'll pretend this folder is called MacPro(001122334455). Then within that folder, as PP is running in motion-detection mode, it creates a new folder based on the current date and then, within that, places videos when motion is detected. Very straight-forward and it works just fine.
    What I would like to do is have a folder action that (a) detects when any new folder or file is created within MacPro(001122334455) and (b) sends me a text-message via Apple Mail.
    If the MacPro(001122334455) folder is empty, I can create a Folder Action that will detect the creation of a sub-folder when the first motion-detected video is created and that successfully sends me a text-message, BUT if a second video is created later within the same date-named folder, I will not get a message. I would get a text-message on the following day as a new folder is created within MacPro(001122334455) that signals the first motion-detected video of the day, but again not subsequent videos on the same day.
    The text-message via Apple Mail I have easily scripted via Applescript and it works flawlessly.
    Since Folder Actions only work upon a single pre-defined folder and not on sub-folders, I can never get automatically notified via text-message of second/third/fourth/etc. motion-detected videos as they're created... only the first one of each day.
    So, I'm wondering whether there's a different way, perhaps through launchd that I might script this process. I'm thinking that if the contentModDate value of the MacPro(001122334455) folder could be read, compared with the last known value, and then---if different---execute the Applescript. OR PERHAPS I'm going about this all wrong and you might have another, better idea?
    I'm open to suggestions.
    -- David (da2357)

    Well, I found a solution that does not use a Folder Action. Since Folder Actions will only work upon the specified folder and not upon the contents of any sub-folders, I needed a different solution.
    First, I launched Terminal and created a new file called monitorPeriscope. I set executable permissions (chmod 700 monitorPeriscope). The contents of the file:
    #!/bin/bash
    # monitor the size of a specified folder and
    # when the size increases, run an applescript
    # copyright 2013, david dot allie at me dot com
    # you are welcome to use this script, but please attribute authorship.
    # CONSTANTS
    WATCHFOLDER="/users/xadmin/movies/com.zipzapmac.Periscope-Pro"
    SIZEFILEONE="/users/xadmin/.bin/foldersizeone"
    SIZEFILETWO="/users/xadmin/.bin/foldersizetwo"
    MYAPPLESCRIPT="/users/xadmin/documents/dropbox/programming/applescript/motion_de tected_text.scpt"
    # START
    # calculates current size of watchfolder, saves to sizefiletwo, then
    # performs a diff operation, result which is evaluated in if statement,
    # and if different, runs applescript, and copy sizefiletwo to sizefileone
    du -h -k -d3 -c $WATCHFOLDER | awk 'END{print}' | awk '{print $1}' > $SIZEFILETWO
    diff --brief $SIZEFILEONE $SIZEFILETWO
    if [ $? -eq 1 ]
      then
        osascript $MYAPPLESCRIPT
        cp -f $SIZEFILETWO $SIZEFILEONE
    fi
    exit 0
    Next, I created the following Applescript, replacing Some User, [email protected] and the text address of [email protected] below with my real values.
    using terms from application "Mail"
    tell application "Mail"
    set theName to "Some User"
    set theAddress to "[email protected]"
    set theContent to "Motion detected in OFFICE."
    set newMessage to make new outgoing message
    tell newMessage
    make new to recipient at end of to recipients with properties {name:theName, address:theAddress}
    set visible to true
    set sender to "[email protected]"
    set subject to "ALERT "
    set content to theContent
    send newMessage
    end tell
    end tell
    end using terms from
    Next, using the touch command, I created /users/xadmin/.bin/foldersizetwo and /users/xadmin/.bin/foldersizetwo as needed for the bash shell script (touch /users/xadmin/.bin/foldersizeone and touch /users/xadmin/.bin/foldersizetwo).
    Next, still in Terminal, I navigated to ~/Library/LaunchAgents and created the following plist using nano, which I named com.xadmin.monitorPeriscope.plist:
    <?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>Disabled</key>
              <false/>
              <key>Label</key>
              <string>com.xadmin.monitorPeriscope</string>
              <key>ProgramArguments</key>
              <array>
              <string>/users/xadmin/.bin/monitorPeriscope</string>
              </array>
              <key>RunAtLoad</key>
              <true/>
              <key>StartInterval</key>
              <integer>900</integer>
    </dict>
    </plist>
    Finally, all that was needed was to log out and then log back in. Once I launched the Periscope Pro app and started the motion-detection mode, I left my office... and within fifteen minutes I received a text message indicating that motion had been detected in my office. In the plist above, I set a StartInterval of 900 seconds, which corresponds to 15 minutes. I can reduce it down to 300 seconds (5 minutes) without it adversely affecting performance, but I'm going to leave the setting where it is for now.
    So, I solved my own problem and I'm pleased with the results.
    -- David

Maybe you are looking for

  • The status of sales order is being in processed

    Dear All, The delivery quantity is fully delivered and it is order related billing, this is a Sales Bom, the header is delivered and the line items are billed, the status of sales order is being in processed after the completion of the subsequent doc

  • How to set up a wireless network without Internet

    I don't have Internet at home but have a wireless router and an iPhone that wants to communicate with the MacBook pro so that they can exchange info (like my todo list and files and whatnot). Is there a way to set up the router or mbp so that the dev

  • Parked document posting - urgent

    < MODERATOR:  Message locked.  Please read the [Rules of Engagement|https://www.sdn.sap.com/irj/sdn/wiki?path=/display/home/rulesofEngagement] before posting next time. > Hi friends, while posting parked document to the posting using FBV0, giving err

  • I get error 20 when trying to reinstall CS 5.5 on new PC.

    I get error 20 when trying to reinstall CS 5.5 on new PC. I thought I deactivated on old PC first before uninstalling; maybe I didn't? Old PC no longer available. What do I do now?

  • Installation of SharePoint 2013 three-tier farm installation

    Is it an actual requirement that WFE1 and APP1 be separate servers (virtual or physical), or is recommended best practice? And more than that, I was going to make DC1, WFE1, and APP1 all reside on the same virtual server.  I'll take the spitballs, bu