Skip to content

Instantly share code, notes, and snippets.

@akostadinov
Last active October 16, 2024 09:28
Show Gist options
  • Save akostadinov/732392d37efce01f5ab250039127e1f0 to your computer and use it in GitHub Desktop.
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.
#!/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