Skip to content

Latest commit

 

History

History
58 lines (40 loc) · 2.84 KB

File metadata and controls

58 lines (40 loc) · 2.84 KB

Editing Text

Using echo and redirection is a pretty inefficient way to edit files. Instead, there are several terminal-based text editors. Here, we'll talk about a few and how to use them.

nano

These days, nano is the default text editor for many systems, mostly because of its ease of use.

To open, run nano or nano <filename>.

When nano is open, the most important keyboard shortcuts are displayed at the bottom. Here, the notation ^X means to hold down Control and press x at the same time.

vi and vim

vi is one of the earlier Unix text editors, and one of the most enduring. Its small size and modal text editing makes it a favorite for many programmers and sysadmins, but it is not so easy to use as nano.

vim is a modern, extended version of vi, with significantly more features, including plugin support. Often, the command vi will be linked to run vim instead. You may need to install vim for the exercises.

vi is a modal text editor. This means that the meaning of your keypresses changes depending on the current mode.

vi opens in Normal mode. Here, you cannot add text, but can quickly navigate using a variety of key combinations, and you can run commands by typing :command and pressing enter. You can always return to Normal mode by pressing Esc.

In normal mode, you can move your cursor with the following keys:

  • j moves the cursor down one line
  • k moves the cursor up one line
  • h moves the cursor left one line
  • l moves the cursor right one line

To open, run vi or vi filename.

To quit, first enter Normal mode, then execute the command :qa (quit all). To quit without saving, append ! to your command.

To edit text, use one of the following keys from Normal mode.

  • i: start editing at the cursor's location
  • a: start editing after the cursor's location
  • A: start editing at the end of the line
  • I: start editing at the beginning of the current line
  • o: create and edit a new line below the current one
  • O: create and edit a new line above the current one

To save a file, enter Normal mode and run the command :w.

Cutting, copying, and pasting text is very efficient in vi. A few useful shortcuts are (in Normal mode):

  • yy: copies the current line
  • dd: cuts the current line
  • p: pastes the copied content after the cursor or line
  • P: pastes the copied content before the cursor or line

Useful tips

gg in Normal mode jumps to the top of the document, and G jumps to the bottom.

In normal mode, you can repeat an action by first typing a number. Try 10j or 10o and see what happens.

You can use u to undo an action and Ctrl-r to redo it.

Exercise

Install vim and nano

Open a file with nano. Write some lines, then save it. Check that your changes worked with cat.

Repeat the same exercise, but using vi or vim. Now use some of vi's features to rearrange your text.