Reputation: 21
I would like to just add it to Automator and let the user choose the directory in which it runs. One Drive will not upload files with space. I managed to remove all spaces but not remove all spaces from the beginning and the end.
My code:
for f in "$1"/*; do
dir=$(dirname "$f")
file=$(basename "$f")
mv "$f" "${dir}/${file//[^0-9A-Za-z.]}"
done
Upvotes: 1
Views: 956
Reputation: 295687
#!/usr/bin/env bash
shopt -s extglob # Enable extended globbing syntax
for path in "$1"/*; do
file=${path##*/} # Trim directory name
file=${file##+([[:space:]])} # Trim leading spaces
file=${file%%+([[:space:]])} # Trim trailing spaces
if [[ $file != "${path##*/}" ]]; then # Skip files that aren't changed
mv -- "$path" "$1/${file}"
fi
done
Notes:
bash
, not sh
, to ensure that extensions (such as extglobbing and [[ ]]
) are available.dirname
, since we always know the directory name: It's in $1
.extglob
syntax extends regular glob expressions to have power comparable to regexes. +([[:space:]])
is extglob for "one or more spaces", whereas the ${var%%pattern}
and ${var##pattern}
remove as many characters matching pattern
as possible from the back or front, respectively, of a variable's value.mv
when the filename didn't need to change, so we can optimize a bit by checking first.Upvotes: 3