How do I append a range of lines from the current buffer to another file in Vim?
Answer
:[range]write >> filename
Explanation
The >> modifier on :write appends lines to a file instead of overwriting it. This is ideal for collecting excerpts, building a scratch file incrementally, or logging selected lines without touching what's already in the destination file.
How it works
:[range]w {file}writes lines to a file and overwrites any existing content:[range]w >> {file}appends lines to the end of the file instead- If the destination file doesn't exist, it is created
- The range defaults to the whole buffer if omitted (same as
%)
Example
Given this buffer:
1: function setup()
2: install()
3: end
4: function teardown()
5: cleanup()
6: end
Append just the teardown function to a separate file:
:4,6w >> extracted.txt
Append only the current line:
:.w >> notes.txt
Append a visual selection:
:'<,'>w >> snippets.txt
Tips
- Use
%w >> {file}to append the entire buffer to a file - The
>>syntax mirrors shell redirection (>>appends,>overwrites), making it intuitive to remember - Running
:w >> {file}without a range appends the whole buffer