We know we can save a file with :w. If additional filename was provided it will save to that file instead. It is good if you want to make a copy of your currently active file. It’s much easier to just call :w newfile instead of jumping to a shell and cp the file.

That’s not all, we can “save” the file to the stdin of an external program. I know save sounds odd here, it’s more like a pipe, but I wanted to show how it is working. We can do that with :w !. Note that space between w and !. It’s important because :w! force writes the file, while :w !cmd will call an external command and sets the stdin for that process.

An easy way to remember:

  • :w: “Write this file please.”
  • :w newfile: “Write the content into a that file please.”
  • :w!: “I SAID WRITE!”
  • :w! newfile: “I SAID WRITE the content into a that file!”
  • :w !cmd: “Execute cmd and feed that process feed with this.”

Save with sudo

Surly everyone uses sudo always when they have to edit a file that requires root permissions. Usually, I don’t bother doing it and it’s a nice way to prevent an accidental save with an incomplete file. Most of the services are not crying if the file is not complete on save, because the service has to be restarted first, but still easier to me to open it as non-root and “save” as root when I’m done. To do that, we can utilize the tee command.

tee - read from standard input and write to standard output and files

So with this handy tool, we can write a file with sudo:

:w !sudo tee %

That % sign, we will talk about it later, for now: It’s the absolute path of the file.