Linux Exercise: Editing files

Working with vi

Start vi with the file you want to edit as argument. If necessary, vi will create the file for you if it doesn't exist yet. Within vi, make sure you get familiar with, at the very least, the following commands:

  • ESC to switch back to command mode if you were in edit or ed/ex mode.
  • ^, h, j, k, l, $ to scroll through your file.
  • I, i, a, A to switch to edit mode.
  • X, x to delete characters.
  • J to join lines together.
  • /, n, N to search and repeat your search.
  • dd, yy, p to cut, copy and paste lines of text.
  • :%s /old/new/g to search and replace text throughout the file from the ed/ex mode.
  • Modifiers: a number before a command, to repeat this command several times.
  • ZZ to save & exit vi from the command mode.
  • :w, :q, :w!, :q! to write and quit from the ed/ex mode. The exclamation mark forces the action.

Working with other editors

If time permits, see if any of the following editors are available. Read through the manual page and try them out. Find one that works for you.

  • pico
  • nano
  • joe
  • jove
  • emacs

Setting the default editor

In this section we're going to explore the default editor shell variable, $EDITOR. For this we will use the crontab -e command. This command edits your "crontab" file, using your favourite editor. At this stage, it is not important what a crontab file is and what it does. The details are covered in a different exercise. Just make sure you don't try to save this file with nonsense data, as the crontab -e command will have a problem with that. So make sure that whatever you modify in the file, you go back to the original, or delete all contents of the file, before closing the editor.

  1. Look at the current value of the $EDITOR variable.
    • $ echo $EDITOR
      There should be no output, as the $EDITOR variable is not set by default. However, the "default default" editor is vi.
  2. Run the crontab -e command. What editor is used to change your crontab? Exit your editor.
    • $ crontab -e
      You should see that the file is edited using vi.
      Use :q! to exit vi.
  3. Set the default editor to nano. Check what happens if you run the crontab -e command again. Exit nano.
    • $ which nano
    • $ export EDITOR=/bin/nano
    • $ crontab -e
      Quit nano with Ctrl-X
  4. Perform the same steps for any other editors you found on your system.
End of exercise