Ok, here is what I came up with:
- Code: Select all
#!/bin/zsh -f
#
# From: Timothy J. Luoma
# Mail: luomat at gmail dot com
# Date: 2018-11-27
#
# Purpose: Script meant to be used with Hazel to move a file into a sub-folder based on the filename
# e.g. Given a filename "2018 - Christina W - Contract.txt" it will move the file to a folder named "Christina W"
# See <https://www.noodlesoft.com/forums/viewtopic.php?f=4&t=10077&p=26650> for more details
#
# Use entirely at your own risk.
PATH='/usr/local/scripts:/usr/local/bin:/usr/bin:/usr/sbin:/sbin:/bin'
# We start by creating a loop that will run this script once for each input (filename)
for i in "$@"
do
# We check to make sure that the input we received
# corresponds to an actual, existing file
if [ -f "$i" ]
then
# ':r' removes the extension from the variable "$i"
#
# Then there are two sed commands in one
# (the ';' is what separates the sed commands)
#
# 's#[0-9][0-9][0-9][0-9] - ##g' means
# "Look for 4 digits in a row,
# followed by one space
# followed by a "-"
# followed by one space
# and replace it with nothing (i.e. remove/delete it)"
#
# 's# - .*##g' means
# "look for one space,
# followed by a dash
# followed by one space
# followed by anything (that is what is meant by '.*')
# and replace it with nothing (i.e. remove/delete it)"
#
MIDDLE=$(echo "$i:r" |\
sed 's#[0-9][0-9][0-9][0-9] - ##g ; s# - .*##g')
# this will create the directory, if needed
mkdir -p "$MIDDLE"
# this will move the file to the directory
# the "-n' will prevent it from overwriting a file
# by the same name, if one already exists
mv -n "$i" "$MIDDLE"
fi # This closes the 'if' portion of the loop
done # this ends the loop
exit 0
#EOF
Enter that into Hazel as "Run Shell Script" and then use the "Embedded Script" feature.
Click the "Edit script" button and paste the script into the window that pops up.
There may be a more "pure Hazel" way to solve this, but I tend to see everything through the eyes of "Can I write a shell script for that?"
Tested it here and it seemed to work, but standard disclaimers apply: use at your own risk.
Feel free to ask questions if you have any.