Copy Selected Files and SubFolders (without "flattening" structure)

I am trying to code a KM (and/or Shell) solution to do this and can't seem to find an easy solution.

I am starting with an existing INPUT_FOLDER where I select a number of files and subfolders that I want copying:


and want to end up with a new OUTPUT_FOLDER:


containing just those files/subfolders.

Both KM's "For Each of the Selected Files" Action (and the BASH Shell "CP -r" command) flattens the structure and I lose the hierarchy.

Would appreciate your feedback. Thanks.

You can use the Get File Attribute action to get the Parent Path, and extract the hierarchy from that. But perhaps better would be to use a RegEx to extract the hierarchy of interest:

Put these inside of the KM For Each Action, where FilePath is the For Each variable. Note: I tested the RegEx, but the Move is untested.

You will need to change the paths of INPUT_FOLDER and OUTPUT_FOLDER to match your setup.


ACTIONS: Extract Relative File Path

Note: This is a download of ACTIONS, which will be immediately inserted into the current macro at the current location when you import to KM.

Keyboard Maestro Actions.kmactions (906 B)



Hey Steve,

The simplest way to do this is to press C.

Create your new folder wherever you want it, and open it so it's frontmost.

Then press V.

If you want to automate the process then AppleScript is the way to go.

This macro will duplicate the selected items in the front Finder window to a folder named Output_Folder in the Downloads folder.

Duplicate Finder Selection to Another Folder.kmmacros (5.7 KB)

You'll have to be more specific about what you want if you need a different destination.


1 Like

Thanks Chris, I had overlooked the simple Cmd-C and Cmd-V approach which works.
I've also figured the Shell command that also works:

  cp -R -P file_in file_out

Hey Steve,

You probably want to add in a lower-case “p” to preserve various attributes.

cp -pPR sourcePath destinationPath

-p    Cause cp to preserve the following attributes of each source file in the copy: modification time, access time, file flags, file mode, user ID, and group ID, as allowed by permissions. Access Control Lists (ACLs) and Extended Attributes (EAs), including resource forks, will also be preserved.”


1 Like

Oh, yeah...

cp will not preserve Finder comments, whereas AppleScript's duplicate command will do so.