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

How do I write a visual selection to a separate file in Vim?

Answer

:'<,'>w filename

Explanation

How it works

Vim's :w command can take a range, and when used with a visual selection, it writes only the selected lines to a file. This is extremely useful for extracting code snippets, splitting files, or saving portions of text.

The workflow is:

  1. Select the lines you want to save using visual mode (V for linewise)
  2. Press : (Vim auto-fills '<,'>)
  3. Type w filename and press Enter

Variations and advanced usage:

  • :'<,'>w newfile.txt - Write selection to a new file
  • :'<,'>w >> existing.txt - Append selection to an existing file
  • :'<,'>w !pbcopy - Pipe selection to a system command (macOS clipboard)
  • :'<,'>w !xclip - Pipe selection to xclip (Linux clipboard)
  • :'<,'>w !command - Send selection as stdin to any command without replacing text

The key difference between :'<,'>w !command and :'<,'>!command is that the :w version does NOT replace the selection with the output. It only sends the text as input to the command.

If the file already exists and you want to overwrite, use :'<,'>w! filename (with ! after w). Without the bang, Vim will refuse to overwrite existing files as a safety measure.

Example

Suppose you have a large configuration file and want to extract the database section:

[general]
app_name = myapp
log_level = info

[database]
host = localhost
port = 5432
name = mydb

[cache]
driver = redis
  1. Move to the [database] line, press V
  2. Select down through name = mydb with 3j
  3. Type :'<,'>w db_config.ini and press Enter

The file db_config.ini is created containing only the database section. The original file is unchanged.

You can also use :'<,'>w >> all_configs.txt to accumulate multiple selections into a single file by appending.

Next

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