Saving file with sudo without reopening

It happens many time that you open file in vim, make major changes and when you try to save, you realize that you needed to open it as a root.

Well, you do not need to reopen that file and you can save it as sudo with below command:

:w !sudo tee %

Hit enter after typing that in, you will be prompted for a password if required and then you will then get the following message.

Press ENTER or type command to continue

Press ENTERĀ and assuming you actually made some changes, you will then get the following message.

Press ENTER or type command to continue
W12: Warning: File "/etc/vim/vimrc" has changed and the buffer was changed in Vim as well
See ":help W12" for more info.
[O]K, (L)oad File:

Press L and quit the file.

That’s all!