6.2 Using command line text editors

There exist several command line text editors that allow you to modify text files directly from the command line even remotely. Here we will introduce two that are commonly installed on Unix-like systems: nanp and vim.

6.2.1 Using nano

One of the simplest command-line editors widely available is nano. If it is installed on your system, you can start editing a text file “test.sh” with the command

$ nano test.sh

Once nano is started, you will be able to modify a text file by simply typing and you can even use your arrow keys to move around the file. However, there is no support for your mouse.

To then save your changes, quit nano or many other functionalists, you will need to use key-combinations that involve your ctrl key. To write-out (i.e. save) your file, hit ctrl+o, which will ask you to confirm the file name. To quit, hit ctrl+x. You can see a list of options on the bottom of the screen.

6.2.2 Using vim

In 1976, Bill Joy implemented a command-line text editor he called vi, which stands for “visual”. While powerful, most systems these days ship with vim, which is an extension of vi and derives its name from “Vi IMproved”.

To start editing a file “test.sh” with vim, open a console and type

$ vim test.sh

Note that confusingly vim is actually started with the command vi on some systems, while others only have vi - so check on your system which command (vimor vi) is appropriate.

vim offers multiple modes. By default, we enter the command mode. We now need to tell vim what we want to do:

  • Go to insert mode: type i. We can now enter text. For example, write the two lines of code from the example above.
  • To exit back to command mode, press the Esc button on the keyboard.
  • When in command mode, we can give commands starting with a colon :, followed by the command letter, see below for examples. To confirm, press return (the Enter button on the keyboard).
    • :w saves the file
    • :q quits vim
    • :wq saves the file and quits vim
    • :q! quits vim without saving the file
    • :s/x/y/g replaces all occurrences of x with y

Quitting vim can be very confusing at first - in fact, the stackoverflow entry about this question has been visited more than 2.4 million times, which adds up to about 80 people an hour on workdays struggling to quit vim.

But because of its widespread availability on most system and its rich feature set, vim is still one of the most popular text editors today and many codes exclusively use vim for all their coding. So it’s definitively worth having a look at vim, even if it has a somewhat steep learning curve.