Adam Hayward: keeping it real

ADNAM.TWENEX.ORG

Fri, 29 Jul 2005

Editing a file and preserving Modified Time

Suppose you want to edit a file but not change the time modified - how do you do this? This could be useful for Blosxom bloggers, who want to edit their posts, without changing the order they are viewed on a page. Well, I came up with a solution in ksh:

#/bin/ksh
if [ test -a $1 ]
  then
        MTIME=`stat -t %Y%m%d%H%M.%S $1 | cut -d" " -f 9| sed 's/\"//g'`
   else
        MTIME=`date +%Y%m%d%H%M.%S`
fi
if [ "$EDITOR" = "" ]
  then
    pico $1
  else
    $EDITOR $1
fi
touch -t `echo $MTIME` $1

How to use it

Copy the above code and paste it into a file called 'blog'. Now make the file executable with chmod, thus:

$ chmod u+x blog

You can now re-edit old blog entries like this:

$ ./blog path/to/blog-post.txt

When you save and exit your editor will touch the file to update the modified time. Immediately afterwards the script will re-set the modified time back to what it was before editing.

User jlromano pointed out that you can do the same with perl, like this:

#!/usr/pkg/bin/perl
($accessTime, $modifiedTime) = (stat($ARGV[0]))[8,9];
system("$ENV{EDITOR} $ARGV[0]");
utime $accessTime, $modifiedTime, $ARGV[0];

Do you have a better way of doing this? Let me know!

[/techy : edit-keep-same-modtime.html]