Skip to content

Instantly share code, notes, and snippets.

@sbeyer
Last active December 28, 2015 19:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sbeyer/7553560 to your computer and use it in GitHub Desktop.
Save sbeyer/7553560 to your computer and use it in GitHub Desktop.
Shell script to rename files to YYYY-MM-DD/HHMMSS.EXT and if it already exists to YYYY-MM-DD/HHMMSS_1.EXT, YYYY-MM-DD/HHMMSS_2.EXT, YYYY-MM-DD/HHMMSS_3.EXT and so on
#!/bin/sh
# A script that renames files to
# YYYY-MM-DD/HHMMSS.EXT
# and if it already exists to:
# YYYY-MM-DD/HHMMSS_1.EXT
# YYYY-MM-DD/HHMMSS_2.EXT
# YYYY-MM-DD/HHMMSS_3.EXT
# and so on
#
# I need this often and always forget where I put it.
# So this time I put it on the internet! :D
# May it be useful for you, too.
# -- Stephan Beyer, 2013-11-19
#
# No warranty!
# Tested on a GNU system.
if [ -z "$*" ]
then
echo "Usage: $0 filenames-to-rename [...]"
exit 1
fi
for file in "$@"
do
extension=$(basename "$file" | sed -ne 's/^\(.*\)\(\.[^\.]*\)$/\2/p')
filename=$(stat -c %y "$file" | sed 's/\([^ ]*\) \([^\.]*\).*$/\1\/\2/' | tr -d :)
if [ -z "$filename" ]
then
echo Something went wrong for "$file"
continue
fi
mkdir -p $(dirname $filename)
if [ -e "$filename$extension" ]
then
i=1
while [ -e "$filename"_"$i$extension" ]
do
i=$((i+1))
done
newfile="$filename"_"$i$extension"
else
newfile="$filename$extension"
fi
mv -v "$file" $newfile
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment