Blog

03/06/2019

Linux / Unix vi / vim: Open and Switch Between Multiple Files



I am new to Linux sysadmin work. I am using vi / vim text editor to edit files located in /etc/ directory. I open files using

vi /etc/resolv.conf /etc/hosts

I can edit the /etc/resolv.conf file only. How do I switch between the two open files while using vim text editor under Linux / BSD / Apple OS X / Unix like operating systems?


There are various commands and ways to handle multiple open files under vi / vim text editor running on Unix like operating systems.

Sample data files

Create a two text files as follows for demonstration purpose:
$ cat /tmp/foo
You can avoid reality, but you cannot avoid the consequences of avoiding reality.

And
$ cat /tmp/bar
If a man does his best, what else is there?

Syntax

To open multiple files at a time using a text editor called vi / vim use the following syntax:
$ vi file1 file2 fileN
OR
$ vi *.py

Examples

Open demo files, enter:
$ vi /tmp/foo /tmp/bar
OR
$ vi /tmp/{foo,bar}
To list open files:
:ls
Sample outputs:

  1 %a   "/tmp/foo"                     line 1
  2      "/tmp/bar"                     line 0

To switch to next file:
:n
OR
:bn
To switch to previous file:
:p
OR
:bp
To open specific file buffer called 10 (use :ls command to list all open file buffers):
:b10
You can also switch between all open files, using the following syntax:
:b foo
OR
:b bar
Modern text editor such as vim supports enhanced tab completion to get list of open file:
:b [HIT-TAB-KEY]
To save currently open file:
:w

Visual editor

To split the current window vertically:
CTRL+W v
To split the current window horizontally:
CTRL-W s
To switch between vertically open windows i.e. navigate through open windows:
CTRL-W h
and/or
CTRL-W l
To switch between horizontally open windows i.e. navigate through open windows:
CTRL-W k
and/or
CTRL-W j
Once switched you can load file using any one of syntax as discussed above:
:n
:b10
:p

Posted by: SXI ADMIN

The author is the creator of nixCraft and a seasoned sysadmin, DevOps engineer, and a trainer for the Linux operating system/Unix shell scripting. Get the latest tutorials on SysAdmin, Linux/Unix and open source topics via RSS/XML feed or weekly email newsletter.

14/08/2019

How to KVM, QEMU start or stop virtual machine from command line (CLI)

KVM or Kernel Based Virtual Machine is a popular virtualization technology. It allows you to run virtual guest machines over a host machine. To start...
14/08/2019

How to Docker backup Saving and restoring your volumes

Running a Docker volume backup First, we spin up a temporary container, and we mount the backup folder and the target Docker volume to this container....
12/08/2019

How to Start and Enable Firewalld on CentOS 7

In this article, we discuss how to start and enable firewalld. It is highly recommended that you have a firewall protecting your server.Pre-Flight CheckThese...