17 August, 2012 Pankaj

vim (or vi) editor is one of the most popular editor and used by many. Even in the times of advanced GUI based IDEs like eclipse, vi is highly preferred by Unix/Linux users. And this is because of the power vi possesses. This small article is only about few commands in vi for editing multiple files at once.

Please note, all commands in vi editor must be executed in command mode, but not in insert/edit mode. Please 'esc' before executing the below mentioned vi commands.

1. To open multiple files in vi

1
vi file1 file2 file3

Or open all the files in directory

1
2
vi *
vi *.txt

2. Navigating among opened files.

Go to next file

1
:n (colon n)

Go to previous file

1
:N (colon N)

Go to Nth file from current file

1
2
:Nn
:2n (for example)

Go to the first file from anywhere

1
:rew

Go to Nth file from anywhere

1
2
:e#N
:e#3 (go to the 3rd file)

Go to previous file or toggle between last two files

1
:e#

3. See list of opened files

1
:ar

Shows list of opened files with [ ] brackets around current file.

1
:ls

Shows list of files opened with line number of the current cursor position for all files.
In the ls result, current file have '%a' against its filename. And previous file is marked with a # sign.
Means, :e# would toggle between the current file (marked with %a) and previous file marked with a # (hash)

4. Open another file from vi editor.

Once some file(s) already opened in vi, more file can be opened using following command

1
:e <path>/<filename>

Example

1
2
3
:e file4
:e ../file5
:e /home/pankaj/file6

Please note, like this only one file can be opened at once.

Also, once more file is opened with this command, navigation through files isn't possible with :n or :N and neither :ar shows the list anymore.
But navigation or toggling among files are still possible with :e#n or :e# commands and list of files can be viewed using :ls command.

5. Saving a file.

Normal :w works to save a file. But once any file is being edited, that have to be saved before moving to other files.
This can be overridden by force, by adding a ! at the end.

1
:n! or :N! or :e#2! or :e#!

But this will not save the modifications made to the current file.

6. Closing a file

It is possible to close a single file from the multiple opened files.
Command to close the current file

1
:bd

To close a specific file

1
:bd filename

To close a file using buffer id (number shown on the first column on :ls or :buffer command)

1
2
:Nbd
:3bd (example)

To close a range of files using buffer id.

1
:3,7bd

To close all the files

1
:%bd

Tags: unix, vim