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.
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 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:
jmoves the cursor down one linekmoves the cursor up one linehmoves the cursor left one linelmoves 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 locationa: start editing after the cursor's locationA: start editing at the end of the lineI: start editing at the beginning of the current lineo: create and edit a new line below the current oneO: 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 linedd: cuts the current linep: pastes the copied content after the cursor or lineP: pastes the copied content before the cursor or line
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.
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.