Skip to content

Instantly share code, notes, and snippets.

@maxlawton
Created October 4, 2014 21:11
Show Gist options
  • Save maxlawton/be80a0f7b3d64974da73 to your computer and use it in GitHub Desktop.
Save maxlawton/be80a0f7b3d64974da73 to your computer and use it in GitHub Desktop.
Timestamp (prefix) files with their modification date
#!/bin/sh
# mstamp.sh: prefix each file with its modified date
# ==================================================================
function _mt() {
echo $(/usr/bin/stat -t $1 -f %Sm "$2")
}
function _usage() {
cat <<EOF
mstamp.sh
Timestamp (prefix) files with their modification date
USAGE
mstamp.sh [options] <files...>
OPTIONS
-h Help: print this help and exit
-v Verbose: print each rename
-n Dry Run: don't actually apply the timestamp
The following options control the format used to create the timestamp:
-l Long: "YYYY-mm-dd_"
-s Short: "YYYYmmdd-" (default)
-t Time: "YYYYmmdd_HHMM-"
-f Custom: Supply your own, as used by /usr/bin/stat
EOF
}
# ==================================================================
STATUS=0
DRY_RUN=
VERBOSE=
FMT="%Y%m%d-"
while getopts hnvltsf: o
do
case "$o" in
h ) _usage; exit 0 ;;
n ) DRY_RUN=1 ;;
v ) VERBOSE=1 ;;
l ) FMT="%Y-%m-%d_" ;;
t ) FMT="%Y%m%d_%H%M-" ;;
s ) FMT="%Y%m%d-" ;;
f ) FMT="$OPTARG" ;;
esac
done
[ $OPTIND -gt 1 ] && shift $(( $OPTIND - 1 ))
[ "$#" -lt 1 ] && _usage && exit 1
# ------------------------------------------------------------------
# backup the 'field separator' characters and remove spaces from current IFS.
# this allows handling of files with spaces.
SAVEIFS=$IFS
IFS=$'\t\n'
# this for loop iterates through all of the files that we gave the program
# it does one rename per file given
for file in $*
do
if [ -f $file -o -d $file ]; then
target=$(_mt $FMT "$file")"${file}"
if [ $DRY_RUN ]; then
echo ${file} " ~~> " ${target}
else
if [ $VERBOSE ]; then
echo ${file} " --> " ${target}
fi
mv -i ${file} ${target}
fi
else
echo "${file} is not a file." >&2
STATUS=1
fi
done
# reset the IFS
IFS=$SAVEIFS
exit $STATUS
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment