Copy File Contents in Vi | Generated by AI
Copying (or Moving) All Content from One File to a New File in Vi
Based on your vi usage, I’ll assume you want to select and copy/delete the entire contents of a file, then paste it into a new file. Vi doesn’t have a direct “select all” like GUI editors, but you can achieve this efficiently in command mode (press Esc to ensure you’re there). I’ll cover both copy (leaving original intact) and cut/delete (moving content).
Step-by-Step: Copy All Content to a New File
- Open your source file:
vi oldfile.txt - Yank (copy) the entire file:
- Type
gg(go to top of file). - Then type
yG(yank from current position to end of file).
Alternative (Vim-specific, works in Red Hat’s vim): Type:1,$yand pressEnter(yanks lines 1 to end).
- Type
- Open the new file:
- Type
:e newfile.txtand pressEnter(creates/opens the new file).
- Type
- Paste the content:
- Type
p(pastes after cursor; since it’s empty, it pastes at the top).
Alternative: TypePto paste before cursor.
- Type
- Save and exit the new file:
- Type
:wqand pressEnter.
- Type
The original file remains unchanged.
Step-by-Step: Delete All Content and Paste into a New File (Move)
This deletes the original content after copying it.
- Open your source file:
vi oldfile.txt - Yank (copy) the entire file first:
ggthenyG(or:1,$y).
- Delete all content:
- Type
gg(to top). - Then
dG(deletes from current position to end).
Alternative: Type:%dand pressEnter(deletes all lines).
Save if needed::w(overwrites the now-empty file).
- Type
- Open the new file:
- Type
:e newfile.txtand pressEnter.
- Type
- Paste:
- Type
p.
- Type
- Save and exit:
:wq.
Quick Tips
- If you accidentally delete without yanking first, use
uto undo. - To do this across files without opening a new one each time: Yank in first file, then use
vi newfile.txt, paste, and save. - For large files, these commands are fast since vi handles buffers efficiently.
Practice on test files to get the hang of it!
How to Copy Text to Another File in Vim
Vim: Yank (copy) entire file