Updated:

VI is useful in a CLI-only envireonment, especially when changing remote configurations in a service.

Basics

  • vi sample.txt Creates a text file
  • A tilde ~ represents an unused line; if there is an empty line without the tilde, there is a newline or tab character present
  • :q! quits the editor (quit)
  • :w! saves the change in file (write)
  • :w newfile.txt save as newfile.txt
  • :wq! saves the file and quits the editor

Modes in VI

VI is a model editor that has two modes: Command and Insert

  1. Command mode
    • Default mode
    • Enables administrative tasks (i.e. saving the file, executing commands, moving cursor, etc)
    • Use this mode when you want to move around the file without changing it (“a safe place”)
  2. Insert mode
    • Enables you to insert text into file
    • Hit i to change to insert mode
    • Hit esc to get out of insert mode`

Making changes in file

  • Deleting
    • dd: delete a whole line
      • n dd: delete n lines
    • D: delete the text on the right side of the cursor
  • Reverting
    • u: undo the last action
    • Ctrl r: redo the last action

Command mode

  • Searching
    • Special characters must be preceded by a backslash (i.e. \n)
    • Hit Enter: take cursor to the first character of the first match
    • /pattern performs a forward search; it pattern matches the text after the cursor
      • N to continue searching
    • ?pattern performs a backward search; it pattern matches the text before the cursor
      • n to continue searching
  • Search and replace
    • :%s/pattern/replace/gc
      • Replace pattern with replace
      • g changes all occurences (greedy)
      • c asks for confirmation
  • Changing display using :set
    • nu: display line numbers on the left hand side
    • wm: word wrap the text
      • wm=2: set word wrap margin to 2 characters

Tags:

Categories:

Updated:

Leave a comment