Try something like this:
#! /bin/bash
# Config variable(s)
ParentFolder="~/FilingCab"
# arg processing (minimalist :)
FileToMove="$1"
# use sed to extract folder number from filename.
FolderNo=$(echo "$FileToMove" | sed -r -e 's/.*zz([0-9]+)\.pdf/\1/')
# use find to search for subdirectories of parent folder that begin
# with the folder no followed by a '.'
TargetFolder=$(find "$ParentFolder" -maxdepth 1 -type -a -d -name "${FolderNo}.*")
NumFolders=$(echo "$TargetFolder" | wc -l)
if [ "$NumFolders" -eq 1 ] ; then
mv "$ParentFolder/$FileToMove" "$TargetFolder/"
else
echo "Error: $NumFolders beginning with "$FolderNo." found" >&2
exit 1
fi
Note the double-quotes around all the variable names. It's always the safe/correct thing to do but in your case it's essential because the filenames and directory names you gave as examples have space characters in them.
The -maxdepth 1
in the find
command only searches for direct subdirectories of $ParentFolder (i.e. ignores subdirs of subdirs). If that's not what you meant, just remove that part. This find
searches for any subdirectories of $ParentFolder that begin with $FolderNo.
I'm not entirely sure what you mean by "if TargetFolder is not equal to not empty", i'm assuming you meant "is the string $TargetFolder non-empty". Ordinarily, I'd check if $TargetFolder existed and was a directory but since we're getting the directory name from a find -type d
, it can only be empty or a directory. or maybe more if there's more than one beginning with "$FolderNo."
I think it's better to check if we get one and exactly one result from the find. Any other value is an error, and we can't move the file. 0 means no matching folders found. 2 or more means more than one folder beginning with "$FolderNo." was found.
The warning msg to stderr is optional. so is the exit 1
, but recommended. It allows you to call this script from another script and check whether it was successful or not.
FileToMove="$1"
tofor FileToMove in "$@" ; do
, and addingdone
to terminate the for-loop as the last line of the file. – cas Sep 01 '12 at 15:17-r
in GNU sed and apparently-E
in Mac's sed both tell sed to use extended regular expressions. The main difference between extended and basic regexps is that the some of the syntactically significant characters in regexp(){}+|?*
are treated as literal strings in basic and have to be backslash-escaped to have their special meaning. In extended regexps, the situation is reversed and they have to be escaped to be treated as literal strings. I generally prefer to use extended because with less backslashes, the regexp is IMO more readable and less cryptic. – cas Sep 02 '12 at 01:00-r
in GNU sed is an odd quirk. IMO, it should be-E
to match the same option in GNU grep....but changing it now would break too many existing scripts that use-r
. – cas Sep 02 '12 at 01:02