Edit file vi, not opened by sudo

Opened a file in vi without sudo. Edited some stuff, realized you can't save it. You close the file, open with sudo, redo the edits.

How about, switching to sudo while vi is still open?

Here's what you got to do:

  1. Open file and edit normally. vi filename

  2. Edit normally.

  3. Try saving as you usually do. :w . Meet the error
    E212: Can't open file for writing
    Press ENTER or type command to continue

  4. Choose to type the command, just type :w !sudo tee %

  5. Press "O" for Ok. Exit vim with :q!

Your edits are saved.