14

There are times when I want to test changes to a file before I overwrite the original. Is there any way I can save a file being edited to a new file?

200_success
  • 9,549
  • 5
  • 51
  • 64
Dom
  • 3,314
  • 5
  • 21
  • 38

4 Answers4

23

You can give a parameter to the :w or :write command to save to a different file. For example to save the current buffer to /tmp/data.txt:

:w /tmp/data.txt

However, keep in mind that this does not switch your buffer to that other file. So if you keep editing and do just :w, that will save to the current file, not to the other one. To switch to the other file, use the :edit command:

:e /tmp/data.txt

To do this one step, save to another file and switch to it, use the :saveas command:

:sav /tmp/data.txt
janos
  • 2,818
  • 2
  • 14
  • 27
  • It's also good to keep in mind that vim will complain if you make any changes to the current buffer without saving/writing them to the current file before running e: /tmp/data.txt – Display name Aug 29 '20 at 17:21
  • But, I suppose :sav overrides writing changes to the original file so it essentially combines :w and :e!. – Display name Aug 29 '20 at 17:29
6

Vim has a "backup mode" that can be enabled by :set backup or :set patchmode. In that mode, Vim automatically keeps a backup copy of files that you write.

For example, if you issue :set patchmode=.orig, and you edit an existing file somefile.txt, then when you issue :w normally, Vim will keep a copy of the old file as somefile.txt.orig and save the new contents as somefile.txt.

200_success
  • 9,549
  • 5
  • 51
  • 64
0

Yes, there is a way. :w new_file_name

Nebril
  • 3,427
  • 4
  • 16
  • 13
0

Simply specify a newfilepath at the :w command - :w newfile.foo

Kiteration
  • 240
  • 1
  • 8