Reputation: 212178
Normally, you don't actually edit a file in vim. If you run vim foo
, edit, write and quit, vim unlinks foo
and creates a new file and a new link named foo
. But, if the file has more than one link, then vim
actually modifies the file. For example:
$ ls -i foo
19428852 foo
$ vi foo
$ ls -i foo
19428857 foo
$ ln foo bar
$ vi bar
$ ls -i bar
19428857 bar
I've been looking around for a way to actually edit a file, and it seems there are two choices. Use ed
, or use vim
but ensure that there are at least two links to the file before I edit. I suppose the question is academic, as it doesn't really matter that vim creates a new file if there is only one link, and vim seems to do the right thing if links are created while the editing is underway, but I'm curious:
is it possible to make vim always edit the file, and not create a new one?
Upvotes: 8
Views: 5065
Reputation: 31
The trick is to tell Vim to use a backupfile to allow the original file to be safely overwritten, otherwise Vim would write to a new file and then rename it to replace the original.
And then tell Vim to write the backupfile nowhere. This way the regular write command will fail, and write must be forced.
:set noswapfile
:set backupcopy=yes
:set backupdir=''
:e big
(hit Crtl-C to stopo line count and syntax highlight)
(edit the file)
:w!
To really see what is going on at the file system level, I used inotify tools:
inotifywait -m -r /path/to/my_test_dir/
But be careful, this does not work well for very big files, for example, I was trying to edit a 10G file in place with this method and ended up with a truncated file of 1.5GB, and the rest of the data was lost. And Vim ended up using almost 2GB of RAM...
Other option would be to use MMap functions, eg. in a Python command line.
Upvotes: 3
Reputation: 2239
Quick google shows this link - Editing a hard link to a file. The command that controls that is
set backupcopy=auto,breakhardlink
Upvotes: 2
Reputation: 10582
Check out the help for the backupcopy
option and the notes on crontab
in particular. The short answer is
:set backupcopy=yes
Upvotes: 13