Last active
October 16, 2024 09:28
-
-
Save akostadinov/732392d37efce01f5ab250039127e1f0 to your computer and use it in GitHub Desktop.
Find and rename files and directories with characters that windows does not support.
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/env bash | |
# run like: | |
# $ find_and_rename_bad_windows_filenames.sh mypath1 mypath2 | |
# You may need to run a few times in case there are multi-spaces at beginning or end of files. | |
# All can be done in one go but too lazy to optimize further. | |
find_regexp='.*/[^/]*[<>:"\\|?*'$'\b'$'\t''][^/]*' | |
#tr_from='<>:"\\|?*\b\t' | |
#tr_to='\-\-\-\-\-\-@\- ' | |
export IFS= | |
# replace bad characters from filenames | |
find "$@" -depth -regex "$find_regexp" -print0 | \ | |
while read -r -d "" badfile; do | |
dir="${badfile%/*}" | |
filename="${badfile##*/}" | |
# filename=" "$'\b'"\\*\"?<>:|" | |
# newname=`echo "$filename" | tr "$tr_from" "$tr_to"` | |
newname=${filename//$'\t'/ } | |
newname=${newname//$'\b'/ } | |
newname=${newname//\\/-} | |
newname=${newname//\*/-} | |
newname=${newname//\"/_} | |
newname=${newname//\?/@} | |
newname=${newname//\</-} | |
newname=${newname//\>/-} | |
newname=${newname//:/-} | |
newname=${newname//\|/-} | |
mv -i -v "$badfile" "$dir/$newname" | |
done | |
# remove also leading and trailing whitespaces from files | |
find "$@" -depth \( -name "* " -o -name " *" -o -name "*." \) -print0 | \ | |
while read -r -d "" badfile; do | |
dir="${badfile%/*}" | |
filename="${badfile##*/}" | |
newname="${filename## }" | |
newname="${newname%% }" | |
newname="${newname%%.}" | |
mv -i -v "$badfile" "$dir/$newname" | |
done |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment