Skip to content

Instantly share code, notes, and snippets.

@monomon
Last active October 26, 2017 08:49
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save monomon/2570ded76da135a6dc45d515e4888d10 to your computer and use it in GitHub Desktop.
Script to timestamp files with their last modification date, optionally adding a counter
#!/bin/bash
# timestamp passed files
# by inserting the date into the filename
#
# The linux `rename` command is great, but it doesn't allow
# inserting a consecutive counter into the filename
# if there is a conflict.
#
# Also, there is the amazing Thunar Bulk Rename tool,
# which has tons of features,
# but hell, let's do this.
# some perl regexes
timestamp_regex='s/([a-zA-Z_]+).*.([\w]{3})/$1-$ENV{timestamp}.$2/'
timestamp_regex_with_counter='s/([a-zA-Z_]+).*.([\w]{3})/$1-$ENV{timestamp}-$ENV{index}.$2/'
function timestamp_file {
fn=$1
curr_index=$2
# arguments contain full path (e.g. from fzf), so get basename
d=$(dirname "${fn}")
# use basename for renaming - otherwise need more complex regex
filename=$(basename "${fn}")
# get last modification date
timestamp=$(date -r ${fn} -I)
# create the new file name
newname=$(echo "${filename}" | timestamp=${timestamp} perl -pe ${timestamp_regex})
# test if the file exists already
# if it does, append a counter to the name
if [ -f $d/${newname} ]; then
echo "File ${newname} exists. Trying with counter..."
timestamp_file_with_counter $fn $curr_index
return $?
fi
echo "renaming to ${newname}"
mv ${fn} ${d}/${newname}
return 0
}
function timestamp_file_with_counter {
fn=$1
curr_index=$2
# arguments contain full path (e.g. from fzf), so get basename
d=$(dirname "${fn}")
# use basename for renaming - otherwise need more complex regex
filename=$(basename "${fn}")
newname=$(echo "${filename}" | timestamp=${timestamp} index=${curr_index} \
perl -pe ${timestamp_regex_with_counter})
((curr_index+=1))
# if it still exists, then recurse into timestamp_file_with_counter
if [ -f ${d}/${newname} ]; then
echo "File ${newname} still exists. Incrementing counter..."
timestamp_file_with_counter ${1} ${curr_index}
return $?
fi
echo "Renaming to ${newname}"
mv ${fn} ${d}/${newname}
return 0
}
filenames="${@}"
index=1
for f in ${filenames[@]}; do
timestamp_file ${f} ${index}
echo "returned with status $?"
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment