Created
March 31, 2023 19:20
-
-
Save 9072997/2336da26dad7f7577e8e3ee9075912e8 to your computer and use it in GitHub Desktop.
a script to recursively shorten all the file names in a directory
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 | |
# this is a script to recursively shorten all the file names in a directory | |
function shorten() { | |
cd "$1" | |
pwd | |
# rename all the files in the directory to numbers | |
# if nessisary, move them to the temp directory to avoid name collisions | |
i=1 | |
tempDir="" | |
for file in * ; do | |
# get the file extension if it exists, including the dot | |
base="${file%%.*}" | |
extension="${file#$base}" | |
newName="$i$extension" | |
# is there annother file in our way? | |
if [ -e "$newName" ] ; then | |
# create a temp directory if we don't already have one | |
if [ -z "$tempDir" ] ; then | |
tempDir="$(mktemp -d)" | |
fi | |
# move the file to the temp directory | |
mv "$file" "$tempDir/$newName" | |
else | |
# just rename the file | |
mv "$file" "$newName" | |
fi | |
((i++)) | |
done | |
# if we had to relocate some files | |
if [ -n "$tempDir" ] ; then | |
# move them back to the original directory | |
mv "$tempDir"/* . | |
# remove the temp directory | |
rmdir "$tempDir" | |
fi | |
# recursively call this function on all the subdirectories | |
for file in * ; do | |
if [ -d "$file" ] ; then | |
shorten "$file" | |
fi | |
done | |
cd .. | |
} | |
dir="$1" | |
if [ -z "$dir" ] ; then | |
dir="." | |
fi | |
shorten "$dir" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment