Last active
December 21, 2020 01:10
-
-
Save Raiu/395e0cd1c3a41a4df4ccfecbe1aabbf7 to your computer and use it in GitHub Desktop.
Bash script to sanitize file and dir names
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
VERBOSE=false | |
NOACTION=false | |
while getopts :hvn opt; do | |
case $opt in | |
v) | |
VERBOSE=true | |
;; | |
n) | |
NOACTION=true | |
;; | |
h) | |
usage | |
exit 1 | |
;; | |
*) | |
echo "Invalid option: -$OPTARG" >&2 | |
usage | |
exit 2 | |
;; | |
esac | |
done | |
shift $((OPTIND - 1)) | |
if [ ! -z "$1" ]; then | |
if [ "$1" = "." ]; then | |
WORKDIR=$PWD | |
elif [ -d "$1" ]; then | |
WORKDIR="$1" | |
else echo "${1} doesn\'t exist" | |
fi | |
else | |
echo "No dir supplied" | |
exit 1 | |
fi | |
sanitize () { | |
echo "$1" | sed -E ' | |
s/[^A-Za-z0-9.\_\-]/./g | |
s/^[^A-Za-z0-9]//g | |
s/\.$//g | |
s/\.{2,}/./g | |
s/[\.\-]{2,}/-/g | |
s/[\.\_]{2,}/-/g | |
' | |
} | |
readarray -t RLIST < <(find ${WORKDIR} -not -path '*/\.*' -type f -printf "%p\n") | |
readarray -t -O "${#RLIST[@]}" RLIST < <(find ${WORKDIR} ! -path ${WORKDIR} -not -path '*/\.*' -type d -printf "%d %p\n" | sort -nr | sed -e 's/^[0-9]\+\s//;') | |
for value in "${RLIST[@]}"; do | |
old="${value##*/}" | |
new=$(sanitize "${old}") | |
if [ "$old" != "$new" ]; then | |
newfp="${value%/*}/${new}" | |
if [ -f "$newfp" ]; then | |
printf "ERROR | Rename\n%s --> %s\n" "$value" "$newfp" | |
else | |
if [ $NOACTION = true ]; then | |
printf "Rename: %s --> %s\n\n" "$value" "$newfp" | |
else | |
if [ $VERBOSE = true ]; then printf "Rename: %s --> %s\n\n" "$value" "$newfp"; fi | |
mv -n "$value" "$newfp" | |
fi | |
fi | |
fi | |
done |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment