Cheatsheet Pages / Vim Cheatsheet
How to save a file in Vim that you forgot to open with sudo — :w !sudo tee %
You edited a system file as a normal user and Vim refuses to save it — and you do not want to redo the edits as root.
Almost every entry was run headless in Vim 9.1 and the resulting file checked; the few entries a tiny build cannot run (system clipboard, persistent undo, the sudo save) were verified against Vim's own documentation instead.
:w !sudo tee %
" Vim pipes the whole buffer to `sudo tee`, and tee (running as root)
" writes it back over % — the file you forgot to open with sudo.
" On a machine without sudo, any privileged writer works the same way:
" it is the `:w !cmd` plumbing that matters.
