I'm very new to scripting and Automator but I am trying to figure out a way to have folders automatically moved to a desired location based on the beginning and ending of their names. for example:
If folder name starts with "A" and ends with "45" move to Documents/Archive/A/45
or
if folder name starts with "J" and ends with "29" move to Documents/Archive/J/29
Edit:
- Real world folder name would be: A761245 or J647929
- Yes the destination folders already exist
- No, the source folder and destination folder are in different locations.
- I'm running macOS Mojave 10.14.6
Is there a way to do this with automator or scripting? Thank you!
Best Answer
I opened Terminal, which by default opens to ones home directory, and ran the following command:
This created two new directories,
A761245
andJ647929
, in the root of my home directory and the hierarchal directory structure within myDocuments
directory to receive them when moved.I then use the following compound command to move any directory whose name started with an upper case alpha character followed by six numeric characters:
The result of this compound command was:
This compound command could be used in a
bash
script, e.g.:This basically works by testing the name of any directory passed to conform to an upper case alpha character followed by six numeric characters using capture groups and
BASH_REMATCH
to build the appropriate destination pathname for themv
command.I know you said the destination directories already exist and the example
bash
code above takes that for granted without any additional error handling. With that said though, you could add a line of code that would create the necessary hierarchal directory structure first, as in the example below:The one-liner compound command would be:
I'd use this version of the compound command and or
bash
script.Note: Using the
-p
option with themkdir
command will create the hierarchal directory structure as needed without erring out if it already exists. This would be that way I'd go just to make sure you do not try moving a source directory to a nonexistent destination directory.