It has happened to me a lot of times that i edit a file in vi. I insert and edit a lot and finally when I try to save it I find that I dont have permission for it. If only I had opened it with sudo. I found a solution for this issue. It was actually a simple command and here it is
:w !sudo tee %
Just use the above command in command mode in vi and that’s it and it will ask for reloading the file and then reload it and exit it using :q!
because we have already written to the file and no need to save the file again.
Try it out and tell me.