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

How do I save just the visually selected lines to a new file?

Answer

:'<,'>w {filename}

Explanation

After making a visual selection, you can write only those lines to a new file using :'<,'>w {filename}. Vim automatically fills in the '<,'> range when you press : from visual mode, and the :w command with a filename writes just that range to the specified file.

How it works

  • Select lines with V (line-wise visual mode) then press :
  • Vim inserts '<,'> — the marks for the start and end of the last visual selection
  • Append w {filename} and press Enter
  • The selected lines are written to {filename}, creating it if needed
  • Your current buffer is unchanged

Example

Given a file with 10 lines, select lines 3-7 with 3GV7G, then:

:'<,'>w /tmp/extracted.txt

This creates /tmp/extracted.txt containing only lines 3-7.

To append to an existing file instead of overwriting it:

:'<,'>w >> /tmp/extracted.txt

Tips

  • Works with character-wise (v) and line-wise (V) visual selections — with character-wise, only complete lines containing the selection are written
  • Use :'<,'>w! {filename} to forcefully overwrite an existing file
  • You can also specify a range directly without visual mode: :5,10w output.txt
  • Combine with :r in another session to insert the extracted lines: :r /tmp/extracted.txt

Next

How do I open the directory containing the current file in netrw from within Vim?