Sometimes I find the need to copy a file's timestamp to another file. For example, when I do batch conversion of video files (e.g. via VisualHub), the converted files' timestamps are all based on the current date. Subsequently when I import them in iMovie, I have to spend some effort to get them to show the correct date. It would be nicer if the converted files' timestamps were exactly the same as the original ones.
So I created this shell script, which allows you to copy the timestamp from one file to another.
#!/bin/bash
if [ $# -ne 2 ]; then
echo "Usage: `basename $0` timestamp_src dest_file";
exit 1;
fi
function printtimestamp()
{
stat -n -f "%Sm" -t "%Y%m%d%H%M" "$1"
}
SRC=$1
DST=$2
if [ ! -f "${SRC}" ]; then
echo "Error: ${SRC} does not exist.";
exit 1;
fi;
if [ ! -f "${SRC}" ]; then
echo "Error: ${SRC} does not exist.";
exit 1;
fi;
TIME_SRC=`printtimestamp "${SRC}"`;
touch -t ${TIME_SRC} ${DST}$ ./cptime.sh timestamp_src dest_file
This will copy the timestamp of the file timestamp_src to the file dest_file.
Even better, I created another script to batch copy timestamps from one directory to the same files in the current directory with a different extension. For example, if I want all the converted *.MOV files in ~/converted to have the same timestamp as the original *.MPG files in ~/orig, I would run this next script like so:
$ cd ~/converted
$ ./modtime.sh MPG MOV ~/orig
The source for this script (modtime.sh) is below.
#!/bin/bash
if [ $# -ne 3 ]; then
echo "Usage: `basename $0` old_ext new_ext old_dir";
exit 1;
fi
function printfilename()
{
echo "$1" | awk -F'.' 'BEGIN { ORS="" } { print $1 }'
}
function printtimestamp()
{
stat -n -f "%Sm" -t "%Y%m%d%H%M" "$1"
}
EXT_OLD=$1
EXT_NEW=$2
DIR_OLD=$3
for f in `ls *.${EXT_NEW}` ; do
FILE_OLD=`printfilename "${f}"`
FILE_OLD=${FILE_OLD}.${EXT_OLD}
FILE_OLD=${DIR_OLD}/${FILE_OLD}
if [ ! -f "${FILE_OLD}" ]; then
echo "Error: ${FILE_OLD} does not exist.";
exit 1;
fi;
TIME_OLD=`printtimestamp "${FILE_OLD}"`;
TIME_NEW=`printtimestamp "${f}"`;
echo "Changing ${f} timestamp from ${TIME_NEW} to ${TIME_OLD}";
touch -t ${TIME_OLD} ${f}
done
Remember to make both scripts executable (chmod +x scriptname). Hope some of you find this hint useful!
Mac OS X Hints
http://hints.macworld.com/article.php?story=2009071909120699