MacOS – How to edit a file without altering its modif date

command linefilemacostext-editor

How can I edit a file without altering its modification dateĀ ? In command line. Is vi able to thatĀ ?

Best Answer

The only way I can think of is to store it's modification date before altering it and then to set it back again.

I'm not aware of any CLI tool that would allow you to do that, however years ago I've written something in C that I used to set the modification date on a file to arbitrary value. I know this is not the answer that you're looking for, but I would do this the following way:

  1. get the original access time and the modification time for a file, before you alter it. For this, you can just use stat() system call (read more about it by issuing man 2 stat).
  2. alter the file, using vi or any other editor you like
  3. set the modification time back to what it was. This can be done using the utimes() call (again, you can read more by issuing man 2 utimes command). Please note, utimes() sets both the access time and the modification time.

Edit

Actually it seems like there's already a CLI tool that can do that. According to this answer: How to change the creation (st_birthtime) date/time of a file in Lion?, you can use touch command to change those times: touch -m changes the modification time and touch -a changes the access time (you can use both options in one call). All you'd need to do then is use the stat command line on the file before you modify it and display its access and modification times. Then do the edit and after that, use touch to set the access/modification times back to their values from before the edit.