CompTIA Linux+ / LPIC-1 Cert Guide (Exams LX0-103 & LX0-104/101-400 & 102-400) (2016)
Chapter 8. Editing Text
This chapter covers the following topics:
Editing with vi
The vi Command mode
Searching and replacing in vi
Advanced vi usage
The Message Line
Editing in vi
Searching in vi
Options in vi
This chapter covers the following exam sections:
Perform basic file editing operations using vi: 103.8
Much of your time as a Linux administrator will be spent reading and editing text files. Gaining familiarity with the tools available is essential to saving time and reducing mistakes. The LPI exams focus on vi as the default editor for Linux as it is installed on every Linux machine. No matter how much you think emacs rocks, or that pico/nano is much easier to use with the onscreen menus, it’s essential that you have basic vi skills.
vi was originally created in 1976 and was focused on making text editing efficient over slow network connections. In the early 1990s a new project was struck to make a more modern version of vi. Appropriately named vim for “vi Improved,” the project took the ideas behind vi and added features such as multiple windows, a scripting language, and graphical interfaces.
vi and vim refer to different pieces of software, but in casual usage they can be used interchangeably. Throughout this chapter we refer to the editor as “vim.”
“Do I Know This Already?” Quiz
The “Do I Know This Already?” quiz enables you to assess whether you should read this entire chapter or simply jump to the “Exam Preparation Tasks” section for review. If you are in doubt, read the entire chapter. Table 8-1 outlines the major headings in this chapter and the corresponding “Do I Know This Already?” quiz questions. You can find the answers in Appendix A, “Answers to the ‘Do I Know This Already?’ Quizzes and Review Questions.”
Table 8-1 “Do I Know This Already?” Foundation Topics Section-to-Question Mapping
1. From vim’s Command mode you type the letter “i”. What does this do?
a. Begins editing the text at the end of the line
b. Begins editing the text at the beginning of the line
c. Begins editing the text at the current cursor position
d. Inverts the case of the character at the current cursor position
2. Instead of using the up and down arrows, you can use
a. k for up and j for down
b. j for up and k for down
c. Ctrl+d for down and Ctrl+u for up
d. j for up and h for down
3. If you wanted to start a new line above the current cursor position, from Command mode, you would type:
a. I (capital i)
b. i (lowercase i)
c. A (capital a)
d. O (capital o)
4. Which command deletes from the current cursor position to the end of the line?
5. You want to copy 10 lines of text into a named buffer for later use. How do you do this?
6. You want to find the previous instance of the string:
but only if it appears at the beginning of the line. Which command will do this?
a. /^ls a\*
b. ?^ls a\*
c. /$ls a\*
d. ?ls a*
7. You entered:
Into vim and received
In response. What just happened?
a. You asked vim if you were in number mode and it responded no.
b. You turned number mode off.
c. You turned number mode on.
d. You turned number mode on and also made it permanent.
8. In your vim editor you entered
What did you just do?
a. Moved 10 characters down
b. Moved 10 words to the right
c. Joined the next 10 lines together
d. Jumped down 10 screens
9. You are editing a shell script and want to look at a configuration file at the same time. Which vim command opens up /etc/group in a window to the right of your currently open script?
a. :rsplit /etc/group
b. You have to quit vim to do this.
c. :split /etc/group
d. :vsplit /etc/group
A Tour of the vim Editor
One of the most confusing things about vim is the presence of modes, or states, in the editor. The three modes are
LastLine, also called “ex” mode
Each of these modes is used for different purposes. The Command mode is used for moving the cursor around and doing operations on text. Insert mode is for adding text to your document. LastLine mode is used to invoke more complicated modes such as search and replace or to manipulate split window panes.
The Message Line
The bottom of the vim screen should contain a number of pieces of information that can help you, varying to suit the situation and actions just completed. This section details some of the messages that can appear.
If you’ve just entered vim file1, when the editor opens the file, the message line should contain something similar to the following:
"/home/rbrunson/file1" 57L, 1756C 18,1 Top
The numbers 18,1 on the right side of the message line are the current line and column numbers, and the Top text is the current position of the cursor. This changes to Bot if you entered the last half of the file. The other value possible is All, which simply means that all the contents of the file are currently on the screen.
A new file (one invoked with vim file1) would show the line:
"file1" [New File] 0,0 All
If you are in Insert mode the message line shows:
-- INSERT –
Editing in vi
vim always starts in Command mode, unless you specify differently. True editing (you type a character; that character appears on the screen) takes place in what’s known as Insert mode. The keys you commonly use to invoke Insert mode from Command mode are
i—The most common method of moving into Insert mode is to press the i key, leaving the cursor at the current position. All typing from that point pushes existing text to the right. Think of this as “insert here.”
I—The uppercase I key moves to the beginning of the current line and from there acts like the i key. Think of this as “Insert at the beginning of the line.”
a—The second most common method is to press the a key, moving the cursor one character to the right, essentially behaving like an i key after that. Think of this as “append after current position.”
A—The uppercase A moves to the end of the current line and from there acts like an a key. Think of this as “Append to the end of the line.”
o—Use this key to open a new line under the present line. For example, if you’re on line 3 in Command mode, pressing o drops line 4 down to become 5 and opens a new line 4 that’s empty. Remember this with “open a new line below.”
O—The uppercase O opens a new line at the current line. For example, if you’re on line 3, pressing O drops line 3 down to become line 4 and opens a new empty line 3 for editing. Remember this with “open a new line above.”
Getting back to Command mode is easy: Press the Esc key at least once; many people double-press it just to make sure they’re really there. At any time you can return to Command mode from Insert mode by pressing the Esc key.
Opening a File for Editing
To create a new file in the current subdirectory, you type vi filename.
To create a new file in a particular directory, use the full path: vi /full/path/to/file.
Sometimes you will want vim to open a file with a search string and put the cursor on the first found instance of that string. To accomplish this, enter vi +/string filename.
Other times you’ll want to edit a file and have the cursor jump to a particular line when the file is opened, such as the initdefault line in the
You would enter vi +18 /etc/inittab.
Expect questions about opening files with particular options, searching a file upon opening it, and other ways to start the vim editor. The + command line option tells vim to run that particular command once the file is open.
Navigating Within a File
The vim editor uses the following keystrokes to move left, right, up, and down, but if you have cursor keys, you can use them, too. Here are some useful keystrokes:
h—This is the left arrow; it’s easy to remember because it’s the leftmost key in the four-key set.
j—Use this for the down arrow.
k—Use this for the up arrow.
l—Use this for the right arrow.
Figure 8-1 illustrates how these keys work.
Figure 8-1 Cursor key directions
As you can see in Figure 8-1, one of the ways to remember the keyboard cursor keys is to just look down at the home row and remember that h is the leftmost, j goes jown (down), k goes kup (up), and l is on the right. Makes perfect sense, right?
You’ll see questions about the movement keys on the exam. The arrow keys are a favorite topic, whereas the Ctrl keys don’t get much love. Know those arrow (h, j, k, l) movement keys!
Other keystrokes move you around in vim using the Ctrl key and a letter:
Ctrl+f—Moves forward a page
Ctrl+b—Moves backward a page
Ctrl+d—Moves forward a half-page
Ctrl+u—Moves backward a half-page
G—Moves to a particular line, such as 12G to go to line 12. Without a number, it goes to the end of the file.
Just about any keystroke or action can be done X number of times by prefixing it with a number.
For example, from Command mode to move down 5 lines you would type 5j. Moving 12 words to the right is accomplished with 12W.
A lot of editing, inserting, and escaping back can sometimes leave the message line without some pertinent information showing, such as the name of the file being edited. When you get confused as to where you are or under which filename you saved this iteration of the file, pressing Ctrl+Gwhile in Command mode shows the filename, total number of lines, and current position expressed as a percentage of the total lines in the file.
A useful and largely unknown set of options are the undo operations. You press u in Command mode to undo a single operation or the latest in a series of changes. If you opened a file, made 30 changes, and then pressed the u key 30 times, you would end up with the exact same file you originally opened.
Don’t bother trying U to undo all changes—that’s not what it’s for. Instead, use the :e! keystroke combination to undo all changes since the last disk write to the file. The : takes you to LastLine mode, and the e! command reloads the current file, discarding all unsaved changes.
The most straightforward way to save a file in vim is to enter :w in Command mode. You save the file and can continue to edit it. To remember the w, think of “write”.
When you’ve made changes to a document, vim won’t let you quit normally, such as with :q. One of the most frustrating situations every vim user faces is the dreaded “E37: no write since last change (add ! to override)” message. This error can be fixed only by using the correct additional !character. To exit a file that is read-only or that you don’t want to save the changes to, you must use the keystrokes :q!. This is known as qbang or “quit dammit.”
If the authors had a dollar (US or Canadian) for each time a student got stuck in vim and had to use the above option (:q!) to get out of the session, we would be very rich.
Saving and quitting a given file is simple, too. In Command mode you enter :wq. Think of “write, quit” to remember this command. If you are editing a file as the root user, such as a configuration file, it is common that this file may lack the write permission. This would result in a :wqcommand to fail. Entering :wq! forces the file to be written, as long as the only barrier is a missing write permission.
Two additional methods of saving and quitting a file are available. The first entails entering :x to save and exit. The second is to press ZZ (hold down the Shift key and press the Z key twice); this is my personal favorite and is easy to remember. As :x starts with a colon, the x is a LastLine command (as is wq). ZZ is a Command mode command. The x LastLine command has the added benefit that it won’t save a file that’s already been saved, which makes exiting that much faster on large files.
Read questions carefully when asked about saving and/or exiting the vim editor. Many test-takers have mentioned that the question’s syntax is critical to getting it right. For example, the question, “Which of the following saves and exits a file in vi?” is very different from the question, “Which of the following can be used to save or exit a file in vi?”
Changing or Replacing Text
The following are incredibly useful when you’re altering an existing file and need to change a character, a line, a sentence, or just a word. For example, the c command changes text, and you can add additional modifiers after the command to indicate to vim how much text to change.
cw—Changes a single word from the current cursor position. To change a whole word, you put the cursor on the first character of it.
c$—Changes from the current cursor position to the end of the line, even if that line is wrapped to appear as another line on the screen.
r—Replaces the character under the cursor.
R—Replaces text on the same line as you type until Esc is pressed, but it doesn’t change text on the next line.
Remember to use the force multipliers in the appropriate places. You can easily change multiple words by using 5cw or replace 10 characters with 10r. Some commands don’t accept the force multipliers, such as R, and some behave differently than you might expect. For example,10O will accept text and then repeat it 9 more times.
Deleting Text and Lines
A useful feature of vim is to remove or delete characters, words, or even lines. Be careful to check your deletions and changes, or press the u key to get things back to normal and try it again.
x—Deletes a single character under the cursor
X—Deletes a single character before the cursor
dw—Deletes a single word that’s currently under the cursor, from the cursor position onward
dd—Deletes the current line entirely, regardless of the cursor position in the line
D—Deletes all text from the current cursor position to the end of the line
dL—Deletes all text from the cursor to the end of the screen
dG—Deletes all text from the cursor to the EOF
d^—Deletes all text from the beginning of the line to the cursor
In the lexicon of computer software verbiage, delete in vim stores the cut or deleted string of text in the unnamed buffer for future use. This buffer’s contents will be overwritten by any further cuts or deletions.
How you delete is important on the exam. If asked to delete from the current position to the end of the line, don’t pick or type the keys that delete the whole line—there are no partial credits on the exam!
The Cut, Copy, and Paste Commands
The process of moving text around in vim is a little complex, so practice on a scratch file first. The following keystrokes are used to cut, copy, and paste text in a vim session:
yy—Copies a line of text to the unnamed buffer
3yy—Copies three lines of text to the unnamed buffer
yw—Copies from the current cursor to the end of the word to the unnamed buffer
3yw—Copies three words to the unnamed buffer
p—Pastes the contents of the unnamed buffer to the right of the cursor
P—Pastes the contents of the unnamed buffer to the left of the cursor
Yanking (or copying) lines (the y key) and pasting (the p key) them back in are done on a whole-line basis, whereas yanking a word or several words is done solely on a word basis. Pasting data back in happens to the right of the current cursor position, so take care to put the cursor directly to the left of the desired insertion point. Pasting puts lines as a new entry directly below the current cursor line.
A common use of the cut, copy, and paste commands is in the /etc/fstab file when you’ve added another filesystem or disk. Open the file, find a line similar to the desired new one, and press yy; then move the cursor to the line above the position you want for the line and then press p. The yanked line appears under the current cursor line.
Named and Unnamed Buffers
The vim editor has a total of 27 buffers: 26 named buffers (a–z) and 1 unnamed buffer that is overwritten by each new operation.
Unless you have specified a named buffer, all operations use the unnamed buffer, and two operations right after each other have the second operation overwrite the data from the first operation.
Named buffer operations are always preceded by the double quotation mark (“), which tells the machine that a named buffer operation is to follow.
When you perform named buffer operations, the buffers must be referred to in the command as either a lowercase or uppercase letter of the alphabet (which is part of the command and not sent to the buffer):
Lowercase buffer letter—Overwrites the buffer
Uppercase buffer letter—Appends to buffer
For example, the following string, when entered in Command mode with the cursor in column 1, causes line 1 to copy the next three lines to the named buffer (a), overwriting any contents of that named buffer:
The Message Line echoes the number of lines and the operation, such as
3 lines yanked
The syntax for the editing commands remains the same; just remember to precede the operation with a double quotation mark, a lower- or uppercase character, and then whatever operation you want to perform with that named buffer.
Other examples include
“ayy—Yanks a line to the named buffer (a), overwriting the current contents
“Ayy—Appends the current line to the a buffer
“A3yy—Yanks three lines from the current cursor position and appends the lines to the A buffer
“ap—Pastes the a buffer to the right of the cursor (The case of the buffer letter is meaningless in paste operations.)
Performing single-line operations with named buffers usually doesn’t echo anything to the Message Line, but anything involving more than one line of data echoes the number of lines affected. Word operations are usually not noted in the Message Line either.
Searching in vi
Searching for text in Linux utilities typically follows a common convention. In the less, more, and vim commands, a forward slash followed by a search term searches forward in the file from the current cursor position or the top of the file, highlighting found strings. Initiating a backward search from the cursor position is done with a question mark followed by the string to search for, such as ?sometext.
Searches are performed only in Command mode, so remember to press the Esc key to get back there.
Finding the next occurrence (whether a forward or backward search) is usually accomplished by pressing the unshifted N key to search in the same direction as the original search. You press Shift+N for a search in the opposite direction of the original search.
Searching and Replacing
Searching a document for a given string or character to replace it is commonly performed either in vim while editing a given file or by the sed command on a large set of data. Both vim and the sed command share a common search-and-replace syntax, with small differences that won’t confuse you if you use both. Indeed, learning to search and replace in one will teach you how to use it in the other.
The search-and-replace syntax is as follows:
For example, the following string in vim replaces just the first instance of the string bob in the current line with the string BOB:
To replace all instances of the string bob with BOB in the current line, you would use this line:
The g stands for global or doing the action on every found instance of the string.
To replace all instances of bob with BOB in the entire file, no matter how many exist or how many changes are made to each line, you would use this:
It’s critical that you read the exam question and all its answers (except for a fill-in-the-blank) to see exactly what is being asked for. A percent symbol (%) in front of the search-and-replace string causes vim to search the entire file, and not just the current line.
Regular Expression Searches
Finding matches using regular expression searches in vim is a good thing to know about. A regular expression search is a fuzzy search: You find something you only know a part of.
For example, if you wanted to find all the instances of the word “The” at the beginning of a line, you could use this search:
To find all the instances of the word “kernel” at the end of a line, you could use this search:
In some instances, you need to find a literal instance of a character that otherwise has special meaning, otherwise known as a metacharacter. For example the asterisk (*) means “zero or more of the preceding character,” but you need to search for an asterisk within a string. In this case, escape the metacharacter by prefixing it with a backslash (\). You could use something like this:
/The \* character
Another example might be finding the text “kernel.”, with the period being treated only as a period rather than the metacharacter meaning of “any single character.” Otherwise, you would find kernels, kernel?, kernel!, and so on. To find just kernel., you would use the following:
Finally, matching a range of characters is helpful, such as trying to find all instances of the version number string v2.1 through v2.9. You either have to perform several searches or use something like this:
The square brackets tell vim to match a single instance of the given range, stretching from the first character to the one after the dash. If you wanted instead to find all versions of the word “the,” including “THE,” “THe,” and “tHE,” you would use the following:
However the \c modifier exists to make the search case-insensitive:
Options in vi
You have three methods of specifying options with the vim editor. All have their place, but if you find yourself frequently having to set options manually, try putting them in the ~/.vimrc file. An example is shown here:
The previous code should be placed in the .vimrc file, one option per line, the file being a simple text file in the user’s home directory.
Both /etc/vimrc and ~/.vimrc are read when vim starts up. These files allow users to retain custom settings, with /etc/vimrc applying to all users and ~/.vimrc to only the user.
If you want all users to have the exact same vim options, edit the /etc/vimrc file to set the options.
To set options on-the-fly, enter them at the : prompt, such as :set number, :set noerrorbell, and set tabstop=5. These last only for the current session and have to be repeatedly reset in future sessions.
Your final option for setting an option with vim is on the command line that started vim. For example, to start vim with nonprinting line numbers onscreen, you would use
vim +"set number" file1
The reason for the double quotation marks is the space between set and number; otherwise, you would get a syntax error.
Many options are available in the vim editor. You can view them easily by typing :set all in the editor, or to see which options are currently set for your session, type :set while in the editor. Finally, you can type :set optionname? to find out about that particular option’s status.
For some reason, LPI really wants you to know the options for setting numbers, including the shortcuts for how options are set. Examples of how you could set the numbers option on and off include
:set number—Turns on line numbers (screen only).
:set nonumber—Turns the number option off.
:se nu—This is the shortest string that turns this option on, and putting no in front of the option turns that option off.
Several tasks are part of vim that don’t fit in any other section. Most of these are advanced, such as running external commands, joining lines, and splitting windows. This section covers these in detail.
Running External Commands in vi
A frequent question on the exams is how to run an external command inside vi, such as seeing an ls –l listing of the current directory so you can remember a filename:
:! ls –l
In this, the command ls –l executes, with the command’s output displaying onscreen, and you need only press Enter or enter a command to return to the vim session. If the output scrolls more than one screen, it’s piped to the more command and all the normal movement keystrokes will apply.
It’s irritating in vim to be at the front of a line and want to use the Backspace key to move that line to the end of the previous line. The Backspace key works only on the current line. If you need a line to be joined to the previous line, you can position the cursor anywhere on the first line and press J to cause the second line to be appended to the end of the current line.
Say you have a file named file1 that contains the following text:
This is line 1
This is a longer line 2
This is an even longer line 3
You want to join line 1 and line 2, so you position your cursor somewhere on line 1 and press the J key. The file then looks like the following:
This is line 1 This is a longer line 2
This is an even longer line 3
Putting the cursor on line 2 and pressing J joins line 2 and line 3 in a similar fashion.
Last, but not least, is splitting windows in vim (not available in the original vi editor). When you’re editing a particular file and want to see either another section of that same file or even another file altogether, you can use the following:
:split—This splits the window horizontally, with the same file and lines shown in both windows.
:vsplit—This splits the window on the same file vertically, with the same document shown in both the left and right panes.
Moving between the panes is somewhat counterintuitive because you must press Ctrl+w to wake up the “window” mode followed by a directional key. Pressing Ctrl+w twice in rapid succession simply moves between the available windows in a sequential manner. Pressing Ctrl+w and then an arrow (cursor) key moves the focus to the window located in that direction, as does using the more traditional directional keys such as h, j, k, or l.
To open a second file instead of a copy of the current file, simply add a filename to the split command, :split file2.
To set the height of the newly split window from the split, you could enter:10split /etc/fstab. This command splits the top 10 lines of the screen and displays the contents of the /etc/fstab file therein.
If you wanted to close the split window, you would focus on it by pressing Ctrl+W and then entering :close.
Better yet, after comparing something or getting a filename straight, you can close all the other split windows and just have the current window open by entering :only.
Many times I’ve opened a couple of split windows to see the difference between two files or used the diff command. The easiest way to compare two files and make edits to them is to use the vimdiff command, such as :vimdiff file1 file2.
This loads the two files into a vertically split vim session and uses color and other symbols to show you what is similar or different between the two files. This is useful for comparing a log file before and after a problem or two configuration files to see why one doesn’t work.
You can also manage splits from the command line. To open vim with two files in separate windows, you can use vim –o file1 file2. These will be horizontally stacked, one with file1 above file2. If you would prefer to open two files in a vertically stacked manner, you would type vim –O file1 file2, with file2 appearing to the right of file1 in the interface.
Exam Preparation Tasks
As mentioned in the section “How to Use This Book” in the Introduction, you have a couple of choices for exam preparation: the exercises here, Chapter 21, “Final Preparation,” and the practice exams on the DVD.
Review All Key Topics
Review the most important topics in this chapter, noted with the Key Topics icon in the outer margin of the page. Table 8-2 lists a reference of these key topics and the page numbers on which each is found.
Table 8-2 Key Topics for Chapter 8
The answers to these review questions are in Appendix A.
1. What is the default editor for Linux systems?
2. Which of the following saves and exits a file you are editing in vi? (Choose all that apply.)
3. After opening a file with vi, you want to navigate to the end of the file as quickly as possible. Which of the following, when performed in Command mode, accomplishes this?
4. Which vim command would open the file mytestfile.txt and cause nonprinting line numbers to appear to the left of all file contents? (Choose all that apply.)
a. vim +set number” mytestfile.txt
b. vim --numbers mytestfile.txt
c. vim --setnumber mytestfile.txt
d. vim –o number mytestfile.txt
5. While editing a file with vi, you press Esc to enter Command mode and then use the keystrokes 3+j+4+l. What is the result?
a. Three columns left and four lines down
b. Three columns right and four lines up
c. Three lines up and four columns left
d. Three lines down and four columns right
6. You are editing a configuration file and realize you’ve made a big mistake. Luckily, you haven’t saved. Which command, from Command mode, will reload the file from disk and leave you in the editor?
7. You want to edit a file with vim and have the word string1 highlighted if found. Which of the following accomplishes this in one command?
a. vi +/“string1” file
b. vi /string1 file
c. vi +/string1 file
d. vi --find string1 file
8. While editing a file in vi, you need to display the permissions for the normal files in the current directory. Which command accomplishes this from Command mode?
a. :x “ls –l”
b. :e! ls -l
d. :! ls -l
9. You have made several customizations to your vim editor and want to keep using them every time you use vim. Where is the best place to store your customizations?
10. While in vi, you need to search and replace all instances of the string snark with FARKLE in the current file. Which statement would include everything necessary to accomplish this from Command mode?