Vim or Vi generally used to work with text files from the command line. In order to work with Vim or Vi, we should open the file or multiple files. In this tutorial, we will examine how to open single or multiple files with Vim.
Open File From Bash Command Line
The most popular use case for opening files is using the command line which is generally a bash terminal. If you are using Windows you will use the MS-DOS command-line tool. The file name is provided to the vim command. In the following example, we will open the file named sample.txt .
$ vim sample.txt
But if the file is located other than the current directory we should provide the path of the file too. This path information can be an absolute or relative path according to the current working directory. For an absolute path, the following command can be used.
$ vim /home/ismail/sample.txt
Or relative path can be used like below where the current directory is /home .
$ vim ismail/sample.txt
Open File and Move/Jump Specified Line Number From Bash
Another useful feature to open a file is providing the line number where the cursor will be moved to the specified line after opened. The line number is provided after the file name with the + (plus) sign. In the following example, we will jump to line number 50 after opening the file.
$ vim sample.txt +50
Also, the line number can be used with the absolute and relative file named like below.
$ vim /home/ismail/sample.txt +50
$ vim ismail/sample.txt +50
Open File From Vim Command Line
If you are all ready to open Vim you can also open the file without exiting Vim. Vim provides the :e command which will open a specified file. The e
command is the short form for the edit.
- Press the ESC key for normal mode.
- Type :edit sample.txt or :e sample.txt to open file named sample.txt.
The edit command can be also used to open files with absolute and relative paths like below.
- Press the ESC key for normal mode.
- Type :edit /home/ismail/sample.txt or :e /home/ismail/sample.txt to open file named sample.txt.
You can also use the Tab key in order to autocomplete or navigate files and paths.
Open File Read Only From Vim Command Line
By default opened files will be editable. So you can make changes in the opened file and save these changes. Vim also provides the ability to open a file in read-only mode. This will not change file attributes into read-only. This mode is only enabled with Vim. The file opened as read-only can not be edited or saved with changes.
- Press the ESC key for normal mode.
- Type :r /home/ismail/sample.txt to open file named sample.txt.
Open Multiple files with Vim/Vi
The Vim/Vi can be used to open multiple files. The file names are provided to the vim
command like below.
$ vim numbers.txt log.txt
After opening multiple files with Vim/Vi the first file is displayed by default. Other opened files can be navigated by using the following command where the numbers are the file index.
:b2