There's just no way around the topic of this chapter, as system administrators edit text files daily. Therefore, we decided to cover three commonly used editors – vi, Vim, and nano. If you're more into GUI tools, make sure that you check
gedit, although we won't cover that editor here as it's practically the same as using Notepad on Microsoft Windows. There are various reasons why these editors were chosen, but most importantly, they are installed out of the box on almost all Linux distributions, so they're the most common pre-installed editors. There are situations where additional software installation is not an option, such as air-gapped environments.
We will cover the following recipes in this chapter:
- Learning the basics of the Vi(m) editor
- Learning the basics of the nano editor
- Going through the advanced Vi(m) settings
For these recipes, we're going to use a Linux machine. We can use any virtual machine from our previous recipe. For example, let's say that we're going to use a
cli1 virtual machine as it's the most convenient to use, seeing as it's a command-line-interface-only machine. So, all in all, we need the following:
- A virtual machine with any distribution of Linux installed (in our case, it's going to be Ubuntu 20.10).
- A bit of time to digest the complexities of using the Vi(m) editor. nano is less complex; therefore, it's going to be easier to learn about that one.
So, start your virtual machine and let's get cracking!
Learning the basics of the Vi(m) Editor
Vi and Vim are the text editors of choice for many system administrators and engineers. In a nutshell, the difference between them is that vim (vi improved) has many more capabilities than the original vi (visual editor). You can find these editors everywhere – from all the Unixes and Linuxes to the commercial Linux- or Unix-based software of today. For example, VMware's vSphere Hypervisor has a version of the vi editor built in. The rationale for this is simple – you need to have some sort of standardized editor that can be used to edit various text files available on a filesystem. Over the years, you'll surely find some cutdown version of vi or Vim on various network devices such as switches and routers, and even more complex devices like firewalls. It's just the way it is. If something's Unix- or Linux-based, chances are it's using text configuration files, and text configuration files need a text editor. Pretty straightforward logic, isn't it?
Just as an example – the Vim editor has spinoffs that can be used in a variety of different ways, including vim-athena (created with Athena GUI support), vim-gtk, and vim-gtk3 (created with GTK/GTK3 support), vim-tiny (a slimmed-down version of Vim), and vim-nox. But still, most people that we know of prefer using the good old-fashioned vi or Vim in a CLI.
For this first part of our recipe, we're going to explain the way vi and Vim work and use them to do some most common things, such as the following:
- Moving around a text file that we want to edit by moving the cursor
- Deleting text (we could refer to it as cutting and deleting at the same time)
- Inserting additional content into a text file
- Saving and exiting in the vi(m) editors
- Finding content in a text file
- Copying and pasting text (what vi and Vim refer to as yank and paste)
That's going to be enough for this first recipe. We're going to go back to the advanced vim capabilities in the last recipe of this chapter, where we're going to dig much deeper into Vim and learn how to use much more advanced concepts, such as using regular expressions, line marking, buffers, and sorting.
We just need to check whether vi and Vim are installed on our system. The simplest way to do it is to just go brute-force and issue the following command:
sudo apt-get -y install Vim-tiny busybox Vim dictionaries-common wamerican
Ubuntu doesn't have or use the vi editor by default, so we can just install the
Vim-tiny package to kind of emulate the same thing. Another way to use the vi editor in Ubuntu would be to use the following command:
busybox is a command-line tool that embeds multiple Linux command-line utilities into one, this command is something that we need to be aware of. But also, we need to remember that the intent of
busybox is to have a way to embed multiple popular CLI tools into one, which in turn means that none of these tools are completely the same as their standalone versions.
After installation is done (if needed at all), we're going to start using Vim and learn how to use it via examples. Let's issue the following commands as
cp /etc/passwd /root cp /usr/share/dict/words /root
Take note of the fact that between
/root (the same thing applies to
/root in the second command), we need to hit the spacebar on our keyboard. We're effectively copying the
words files to the
/root directory to have some source files to play with.
When we have successfully finished copying these files, we'll start the Vim editor and start editing. First, we're going to use the
passwd file. Type in the following:
Let's start learning!
How to do it…
Now that we have the
/root/passwd file opened in our Vim editor, let's play with it a bit. Moving around in normal mode is straightforward. Let's just start by using the arrow keys on our keyboard to move up and down and left and right. After we're done with that, let's just jump to the top of our file by using the gg sequence (by pressing the g key twice).
And now, after we have pressed the d key twice, it should look like this (if we are still positioned at the first line, the
As we can see, the first five lines after our cursor (the lines starting with
games) are gone.
Let's now jump to the last line in our
/root/passwd file, and copy and paste it behind the last line. First, we need to go to the end of our file, which can be achieved by using the Shift + g sequence (basically, the capital letter G). After that, if we want to copy the line after the cursor (in effect, complete the last line in the file), we need to first yank it (copy) and then paste it to a correct spot. Yanking can be achieved by using the yy sequence (pressing the y key twice). That puts the line after our cursor in a copy and paste buffer. If we want to paste it after our last line, we need to press the p key. Our copied line will automatically be pasted after the last line. The end result, if we used the same virtual machine as in Chapter 1, Basics of Shell and Text Terminal, should be something like this:
Now, let's select three lines beginning with
sshd (so, the
student lines) and copy and paste them after the line beginning with
joe. First, we're going to use cursor keys to position at the beginning of the
sshd line. Then, we're going to type the y3y key sequence. This will start yanking (copying) from the cursor, copy the next three lines in the copy and paste buffer, and then end yanking. If we did that successfully, Vim is going to throw us a message at the bottom of the screen, saying
3 lines yanked.
After we have these lines in the copy and paste buffer, we need to paste them. Let's use the cursor keys to move to the line beginning with
joe, and then press the p key. The result should look like this:
Now that we have played with yank and paste and delete, it's time to add some content to this file. In order to do that, we need to enter insert mode. That can be achieved by typing the i key. So, let's add a bit of text after our cursor – press the i key and start typing. Let's add the following:
Now that we've done that successfully, the next logical step will be to save the file if we're happy with its contents. Let's say that we are and we're ready to save the file. In order for us to do that, we need to enter ex mode and tell Vim that we want to exit and save. There are several different key sequences that will make this happen for us. The first one is :wq! (write and quit – don't ask us for confirmation), and the second one is :x. There are other ways, such as using the ZZ key sequence, but let's stick to the more commonly used ones (wq and x). We need to make sure that we type these key sequences with a colon sign (:). As we will explain in a bit, using the colon sign means that we want to enter ex mode and do some final operations with our edited file. If we use this key sequence successfully, we should end up in shell, with our original file saved with all the changes that we made to it.
In truth, Vim has a spectacular number of key sequences that can be used for a variety of operations on text files. Feel free to translate this spectacular as either a very good or very bad thing, as it's all subjective – some of us like it a lot, some of us will hate it. Here are some commonly used key sequences:
- dw – delete a word
- 2dw – delete two words
- yw – yank one word
- u – undo the last change
- U – undo changes made to the current line
- a – append text after the cursor
- A – append text to the end of the current line
- Ctrl + f – scroll the file forward by one screen
- n Ctrl + f – scroll the file forward by n screens
- Shift + m – move the cursor to the middle of the page
- :50 – move the cursor to line 50 of the current file
- $ – move the cursor to the end of the line
- x – delete the character at the cursor
- X – delete the character before the cursor
- ^ – go to the first character of the line
- o – insert a line after the current one
- Ctrl + g – print the file info
There are literally hundreds of other commands, and we deliberately selected only some of them that we feel are useful and commonly used. Let's now do some more complex things by using a built-in Vim teaching tool called Vimtutor. In the command line, start Vimtutor by typing the following:
After that, Vimtutor is going to ask us about the intended output file for practice, and we can just press the Enter key here. We should have the following content on our screen:
Let's now use this file to practice a bit. The first thing that we're going to do is copy the first paragraph (starting with Vim and ending with editor.) before the paragraph starting with The approximate time.
Let's position our cursor at the beginning of the Vim line by using the arrow keys. After we have done that, we need to use the y} key sequence to instruct Vim to yank the paragraph starting at the cursor. Then, we need to move to the empty line between the first and second paragraphs by using the cursor keys and pressing the p key to paste the copied paragraph after the cursor. The result should look like this:
- We need to move to the beginning of our file (gg).
- We need to turn on visual mode (more about this a bit later), achieved by pressing the Shift + v key sequence (uppercase V).
- We need to mark the text all the way to the end of our file, achieved by pressing the Shift + g key sequence (uppercase G).
- We need to make the text lowercase, achieved by pressing the u key.
So, the key sequence we're looking for is ggVGu. The result of our operation should look like this:
If we wanted to do the opposite (uppercase all the characters), we'd use the ggVGU key sequence (U is for uppercase and u is for lowercase characters).
We're going to take a short break from all of these key sequences by explaining how Vim works – specifically, we're going to focus on commonly used modes and briefly mention some of the lesser-used ones. Let's start with normal mode and work our way toward visual and replace modes.
How it works…
The Vim editor has more than 10 different modes, which roughly translates into the different ways in which it works. The most used modes are as follows:
- Normal mode
- Insert mode
- Ex mode
- Visual mode
- Replace mode
When we start Vim, we're in normal mode; we can sniff around in it by using the cursor, we can do a bit of yank and paste, and we can delete. So, it's used for general operations such as navigating through an edited file, a bit of rough-cut editing, and that's that.
If we want to add additional content to our text file, we usually switch to insert mode by using the i key. In insert mode, we can easily add a bit of text after our cursor and move around in our edited file. When we're ready to go back to normal mode, we can do that by pressing the Esc key. If, however, we're done with file editing and we just want to save the file and exit, we need to go to normal mode and then to ex mode. This is achieved by pressing the Esc key, followed by the colon (:). That puts us in ex mode, and then we can proceed to do wq!, x, or ZZ.
Visual and replace modes are quite a bit different. Visual mode has sub-modes (character, line, and block), and can be used to select (highlight) parts of the text that we want to work with and manipulate. For example, line and block modes can be useful for modifying YAML files when working with Ansible. Character mode can be used to highlight a part of code. YAML syntax is sensitive to indenting, so by using line mode, we can highlight portions of our playbooks and indent them left or right (by using the > and < keys) so that we don't have to do it manually. Block mode can be used efficiently to check indentation that was created by using line mode. These modes can be entered by using Shift + V (line mode) and Ctrl + v (block mode). Character mode can be entered by using the v key.
- Vim: https://www.Vim.org/
- Mastering Vim: https://www.amazon.com/exec/obidos/ASIN/1789341094/stichtingiccfhol
- An interactive Vim tutorial: https://www.openVim.com/
Learning the basics of the nano editor
If you feel that the Vim editor is too complicated for you, we can feel your pain. That's why choosing the editor you're going to work with is a subjective choice. We'd like to offer another much simpler editor to the table, called nano.
Keep the CLI1 virtual machine powered on and let's continue editing our files.
How to do it…
We're going to edit the
words file that we copied in the previous recipe. Before that, let's just make sure that nano is installed by typing in the following command:
sudo apt-get -y install nano
Let's now open the file called
words from the
root directory by typing in the following command:
Our file should be opened in the nano editor, as shown in the following screenshot:
For those of us who are more prone to using text editors such as Notepad or Wordpad, nano should be a bit more familiar territory. It doesn't have the scope of capabilities or advanced functionality that Vim has, but for the most part, that might not be so important, at least not for most text file editing operations. Or is it really that simple? Let's check it out.
Editing in nano works in the same fashion as with other regular editors – we just need to explain the lower part of the screenshot (the part where we can see
Exit, and so on). In nano, if we need help, we need to press Ctrl + g. This is the result that we'll get:
We can spend our time scrolling through this help window if we want to. But, for starters, let's just say that this
^ character means press the Ctrl key.
So, on our first nano screenshot,
^G means Ctrl + G,
^X means Ctrl + X, and so on. It still isn't as easy as using some text editors that a lot of people use on Microsoft Windows, but it's a bit more user-friendly than Vim. If nothing else, some of the commonly used commands are right at the bottom of our screen so that we don't have to learn all of the key sequences or research them online before we consider using the editor.
If we want to close our help window from the second nano screenshot, we just need to press Ctrl + X. This will get us back to the state shown in the first nano screenshot.
If we want to delete a line, we need to use Ctrl + K. If we need to delete multiple lines, things start to get a bit more complex. We first need to select the content that we want to delete (Ctrl + Shift + 6), use the cursor to move to the place that we want to delete to, and then press Ctrl + K. Let's say that we want to delete five lines. So, selecting content that we want to delete looks like this:
After we have selected the correct text, we just need to press Ctrl + K to delete it. The result will look like this:
The same idea applies to doing a copy and paste operation on a paragraph. We'd use Ctrl + Shift + 6 and the cursor to mark the text, Alt + 6 to put the copied text in the copy and paste buffer, and then use Ctrl + U to paste it wherever it needs to be pasted in nano. Saving the file is equivalent to using Ctrl + X to exit, and then confirming that we want the changes to be saved to a file.
- The nano editor cheat sheet: https://www.nano-editor.org/dist/latest/cheatsheet.html
- How to use nano: https://linuxize.com/post/how-to-use-nano-text-editor/
Going through the advanced Vi(m) settings
In the first part of this chapter, we learned some basic Vim operations, which were moving around, copying and pasting, saving, and exiting. Let's take care of some more advanced operations, such as working with find and replace, regular expressions, and similar concepts.
We need to leave our CLI virtual machine running. If it's not powered on, we need to power it back on.
How to do it…
Finding content in Vim is a multi-step process, and it depends on a couple of things. First, it depends on the direction that we want to take, forward or backward, as there are different key sequences for these operations. Let's open the
/root/words file again to find some text:
Let's start by finding the word
fast. For that to work, we need to use the
/ character from normal mode, as it tells Vim that we're about to use the
search function. So,
/fast will search for the words
fast forward from our cursor. This is the expected result:
However, if we want to find the 10th appearance of the word
fast, we need to either press the correct key sequence or use a regular expression. Let's start with a key sequence, which is going to be (again from normal mode)
10/fast. This is the expected result:
Let's now do a bit of search and replace. Let's say that we want to find all appearances of the word
airplane and change them to
metro, starting from the beginning of our file. The key sequence used for that would be gg (to go back to the file beginning) and then
:%s/airplane/metro/g, followed by the Enter key. This is the expected result:
This syntax presumes the automatic replacement of all occurrences of the word
airplane with the word
metro placed anywhere in the file. If we just wanted to replace the first appearance of a string in any line, we need to first find that word by using the
/word key sequence. Then, we need to use the
:s/word1/word2/ key sequence to only change the first appearance of
word2. Let's use the word
airship for that example and change that word to
ship. If we type in
/airship, followed by the Enter key, Vim will position us to the first next appearance of the word
airship. If we then use the
:s/airship/ship/ key sequence followed by the Enter key, we should get this result:
It's a subtle difference, but an important one.
We're going to stop here, as we will cover more advanced text search patterns by using regular expressions in Chapter 7, Network-Based File Synchronization.
How it works…
String replacement in Vim works by using an external command called
sed, a stream editor. This command is regularly used by system engineers all over the world to quickly replace simple or complex text patterns of any given file (or multiple files) to another complex text pattern. It uses regular expressions as a basis (explained in Chapter 7, Network-Based File Synchronization), which means that, by default, doing search and replace in Vim is quite powerful, albeit a bit complex, as we need to learn the ins and outs of sed and the way Vim treats it as a plugin.
That being said, most of us focus on the quite powerful part of the last paragraph, as using a Vim/sed combination to quickly replace complex text patterns yields fast and precise results – as long as we know what we're doing, of course.
Using these concepts requires a bit of extra reading. So, we need to make sure that we check the following additional links:
- Vim Tips Wiki – search and replace: https://Vim.fandom.com/wiki/Search_and_replace
- Vim tips: the basics of search and replace: https://www.linux.com/training-tutorials/Vim-tips-basics-search-and-replace/