Opening Files
There are two primary methods for opening files in Vim:
Method 1: Open a File from the Terminal
To open a file directly from your terminal, type vim
followed by the filename. For example:
vim /etc/file.txt
Method 2: Open a File from Within Vim
When you launch Vim by simply typing vim
in the terminal, no files are loaded by default. To open a file during your Vim session, use the command:
:e <filename>
For example:
:e /etc/file.txt
Working with Buffers
When you open a file, its content is loaded into what Vim refers to as a "buffer." A buffer is essentially a section of memory that holds the content of a file you’re working with. You may often want to bring content from another file into your current buffer. While you could manually copy and paste between files, Vim offers a more efficient method.
You can use the :read
command (or its shorthand :r
) to insert the content of another file or the output from a system command into your current buffer.
Here are a few examples of how to use it (All of these commands should be executed in Normal mode):
Command | Description |
---|---|
:r main.txt |
Inserts the contents of main.txt below the cursor. |
:0r main.txt |
Inserts the contents of main.txt before the first line. |
:r!sed -n 4,8p main.txt |
Inserts lines 4 to 8 from main.txt below the cursor. |
:r !ls |
Inserts a directory listing below the cursor. |
Note that the last command (:r !ls
) will work only on Linux or macOS.
Closing Files
There are several methods to close a file in Vim, each serving different purposes. Here are some common commands:
Command | Description |
---|---|
:wq |
Saves the currently opened file and exits Vim (even if no changes were made). |
:q! |
Exits Vim without saving the currently opened file. |
:x |
Exits Vim but only saves changes if modifications have been made. |
ZZ |
Equivalent to :x ; simply press this key combination (no colon needed). |
:qa |
Closes all open files in the current Vim session. |
Saving Files
When you save a file in Vim, you’re writing the contents of the buffer to disk, so the commands for saving are referred to as “write” commands. Here are some essential commands to know:
Command | Description |
---|---|
:w |
Saves the currently opened file (if it was previously saved). |
:w file.txt |
Saves the currently opened file as file.txt . |
:w! file.txt |
Saves the file as file.txt , overwriting it if it already exists. |
:sav file.txt |
Saves the current buffer as a new file named file.txt . |
:up[date] file.txt |
Similar to :w , but saves only if the buffer has been modified. |