How can I edit a file without altering its modification date ? In command line. Is
vi able to that ?
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:
- 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).
- alter the file, using
vior any other editor you like
- 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 utimescommand). Please note,
utimes()sets both the access time and the modification time.
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.
You can use touch -t to change the modification and access times, touch -m to change the modification time, or touch -a to change the access time. All of them also change the creation time if the target time is before the original creation time.
$ ls -lT test.txt -rw-r--r-- 1 lauri staff 3 Nov 3 15:13:42 2013 test.txt $ date -jf %s $(stat -f%m test.txt) +%Y%m%d%H%M.%S 201311031513.42 $ vi test.txt $ ls -lT test.txt -rw-r--r-- 1 lauri staff 3 Nov 3 15:18:18 2013 test.txt $ touch -t 201311031513.42 test.txt $ ls -lT test.txt -rw-r--r-- 1 lauri staff 3 Nov 3 15:13:42 2013 test.txt
stat -f%m specifies the format string as the modification time. In date -jf, -j disables setting the time and -f specifies the format.