How do I save a portion of the current buffer to a separate file?
Answer
:{range}w {filename}
Explanation
:w accepts a line range and a filename to write just those lines to a new file. This is useful for extracting a function, a config section, or any block of lines into its own file — without leaving Vim or doing any copy-paste.
How it works
:{range}w {file}— write the lines in{range}to{file}(creates or overwrites):{range}w >> {file}— append the lines to{file}instead- Ranges can be line numbers, marks, or relative expressions:
:10,25w extract.py— write lines 10–25 toextract.py:'a,'bw section.txt— write from markato markb:.,$w rest.txt— write from current line to end of file:'<,'>w selection.txt— write the last visual selection (set automatically when you:in visual mode)
Example
In visual mode, select a block, then type : — Vim prepopulates :'<,'>. Complete it:
:'<,'>w /tmp/snippet.py
The selected lines are written to /tmp/snippet.py.
Append the current function to a log file:
:'{,'}w >> ~/notes/functions.log
Tips
:w!to force-overwrite a read-only or existing file- After writing a range, the original buffer is unchanged — this is a non-destructive operation
- Combine with
:rto move text between buffers: write to/tmp/clip.txtin one buffer,:r /tmp/clip.txtin another - To write the whole file to a different path (Save As), use
:saveas {newfile}— it also renames the buffer