vimtricks.wiki Concise Vim tricks, one at a time.

How do I save only a range of lines to a file?

Answer

:{range}w filename

Explanation

The :w command with a range and filename saves only the specified lines to a new file. This is useful for extracting portions of a file.

How it works

  • :10,20w extract.txt saves lines 10-20 to extract.txt
  • :'<,'>w selection.txt saves the visual selection
  • The original file is not modified

Example

:1,50w header.txt       " Save first 50 lines
:'<,'>w snippet.py      " Save visual selection
:.,$w rest.txt          " Save from current line to end

Tips

  • :w >>file appends to an existing file
  • Without a range, :w file saves the entire buffer
  • :w! file overwrites an existing file
  • This does not change the current buffer's filename
  • Useful for splitting large files into smaller parts

Next

How do you yank a single word into a named register?