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:
- Select the lines you want to save using visual mode (
Vfor linewise) - Press
:(Vim auto-fills'<,'>) - Type
w filenameand 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
- Move to the
[database]line, pressV - Select down through
name = mydbwith3j - Type
:'<,'>w db_config.iniand 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.