Viewing and Editing Files - Linux Administration (2016)

Linux Administration (2016)

Viewing and Editing Files

Here are some simple commands that display the contents of files on the screen.

cat file - Display the entire contents of file.

more file- Browse through a text file. Press Spacebarto advance to the next page. PressEnterto advance to the next line. Typeqto quit viewing the file. Commands are based on thevi editor, which is covered in the next section.

less file - Like more but allows backward movement and pattern searches.

head file - Output the beginning (or top) portion of file.

tail file - Output the ending (or bottom) portion of file.

This is how you might examine a file namedfile.txtwith the commandscat,tail, andmore.

$ cat file.txt

This is the first line.

This is the second.

Here is some more interesting text.

Knock knock.

Who's there?

More filler text.

The quick brown fox jumps over the lazy dog.

The dog was rather impressed.

Roses are red,

Violets are blue,

All my base are belong to you.

Finally, the 12th and last line.

$ head file.txt

This is the first line.

This is the second.

Here is some more interesting text.

Knock knock.

Who's there?

More filler text.

The quick brown fox jumps over the lazy dog.

The dog was rather impressed.

Roses are red,

Violets are blue,

$ tail file.txt

Here is some more interesting text.

Knock knock.

Who's there?

More filler text.

The quick brown fox jumps over the lazy dog.

The dog was rather impressed.

Roses are red,

Violets are blue,

All my base are belong to you.

Finally, the 12th and last line.

$ more file.txt

Here is some more interesting text.

Knock knock.

Who's there?

...

By default, headandtailonly display ten lines. You can override this behavior and tell them to display a specified number of lines. The format is-nwheren is the number of lines you want to display. If you only want to display the first line of a file,usehead -1 file. Want to display the last three lines? Then runtail -3 file.

$ head -2 file.txt

This is the first line.

This is the second.

$ tail -1 file.txt

Finally, the 12th and last line.

$

Viewing Files In Real Time

Usingcatcan be a fine way to view files that have fairly static content. However, if you are trying to keep up with changes that are being made in real time to a file,catis not the best choice. A good example of files that can change often and rapidly are log files. For example, you may need to start a program and look at that program's log file to see what it is doing. For this case, use thetail -f file command.

tail -f file - Follows the file. Displays data as it is being written to the file.

$ tail -f /opt/app/var/log.txt

Oct 10 16:41:17 app: [ID 107833 user.info] Processing request 7680687

Oct 10 16:42:28 app: [ID 107833 user.err] User pat denied access to admin functions

...

Editing Files

Nano

If you need to edit a file right now and do not want to spend any time learning obscure editor commands, usenano.Nanois a clone ofpico, so,if for some reason thenanocommand is not available,pico probably is. It's not as powerful as some other editors, but it's definitely easier to learn.

When you startnano,you will see the file's contents and a list of commands at the bottom of the screen. To run the commands, replace the caret symbol (^) with theCtrlkey. For example, to exitnanotypeCtrl-x.

Editing innanois quite easy. The up and down arrow keys will take you to the previous or next lines as expected. The right and left arrow keys let you navigate forwards and backwards on the same line. Simply type the desired text into the editor. To save the file, typeCtrl-o. If you forget to save the file before you exit,nano will ask you if you want to save the file. To learn more,typeCtrl-g for help.

Vi

Whilenanois great for simple edits,viandemacshave more advanced and powerful features. There is a learning curve to using these editors as they are not exactly intuitive. It will require a bit of a time investment to become proficient. Let's start by looking atvi.

vi [file] - Edit file.

vim [file]- Same asvi, but with more features.

view [file]- Startsvimin read-only mode. Useview when you want to examine a file but not make any changes.

Vimstands for "Vi IMproved." It is compatible with the commands found invi. Some of the additional features ofvim include syntax highlighting, the ability to edit files over the network, multi-level undo/redo, and screen splitting. On many Linux distributions,when you invokevi, you are actually runningvim.

One advantage of knowingviis thatvior avi variant,likevim, is always available on the system. Another advantage is that once you learn the key mappings forvi, you can apply them to other commands—likeman,more,less,view—and even your shell.

Vi Modes

Command Mode

Vihas the concept of modes. You are always working in one of three modes: command mode, insert mode, or line mode. Whenvi starts, you are placed in command mode. To get back to command mode at any time,hit the escape key (Esc). Letters typed while in command mode are not sent to the file, but are rather interpreted as commands. Command mode allows you to navigate about the file, perform searches, delete text, copy text, and paste text.

Here are some commonly used key bindings for navigation.

k - Up one line.

j - Down one line.

h - Left one character.

l - Right one character.

w - Right one word.

b - Left one word.

^ - Go to the beginning of the line.

$ - Go to the end of the line.

Note that commands are case sensitive. For example, if you want to move down one line,type the lowercasej. The uppercaseJjoins lines together. The originalvi editor did not employ the use of arrow keys; however, vim does, so you may find that you can use arrow keys on your system. The advantages of learning the original key bindings are 1) they always work and 2) it's faster since your hand does not have to leave the home row.

Insert mode

To enter insert mode, press one of the following keys.

i - Insert at the cursor position.

I - Insert at the beginning of the line.

a - Append after the cursor position.

A - Append at the end of the line.

After entering insert mode, type the desired text. When you are finished, typeEsc to return to command mode.

Line mode

To enter line mode,you must start from command mode and then type a colon (:) character. If you are in insert mode, typeEsc to get back to command mode and then type a colon for line mode. Here are some of the most common line mode commands you will want to know.

:w - Writes (saves) the file.

:w! - Forces the file to be saved even if the write permission is not set. This only works on files you own.

:q - Quit. This will only works if there have not been any modifications to the file.

:q! - Quit without saving changes made to the file.

:wq! - Write and quit. After modifying a file,this command ensures it gets saved and closesvi.

:x - Same as :wq.

:n- Positions the cursor at linen. For example, :5 will place the cursor on the fifth line in the file.

:$ - Positions the cursor on the last line of the file.

:set nu - Turn on line numbering.

:set nonu - Turn off line numbering.

:help [subcommand]- Get help. If you want more information on the:wcommand type:help :w.

Mode

Key

Description

Command

Esc

Used to navigate, search, and copy/paste text.

Insert

i I a A

Also called text mode. Allows text to be inserted in the file.

Line

:

Also called command-line mode. Save the file, quitvi, replace text, and perform some navigation.


Here is a screenshot ofvim. Tildes (~) represent lines beyond the end of the file.

Advanced Editing withvi

You can repeat commands invi by preceding them with a number. For instance, if you would like to move the cursor up 5 lines,type5k. If you would like to insert a piece of text 80 times, type80iand start entering the text. Once you hitEsc to return to command mode,the text you typed will be repeated 80 times. If you would like to make a line of asterisks, you could type80i*Esc. Can you start to see howviis more powerful than an editor likenano?

Deleting Text

x - Delete a character.

dw- Delete a word. To delete five words, typed5w. The repeating concept invi shows up in many places.

dd - Delete a line. To delete threelines, type3dd.

D - Delete from the current position to the end of the line.

Changing Text

r - Replace the current character.

cw - Change the current word.

cc - Change the current line.

c$ - Change the text from the current position to the end of the line.

C- Same asc$.

~ - Reverses the case of a character.

Copying and Pasting

yy - Yank (copy) the current line.

y<position> - Yank the <position>. For example, to yank a word,typeyw. To yank three words typey3w.

p - Paste the most recent deleted or yanked text.

Undo / Redo

u - Undo.

Ctrl-r - Redo.

Searching

/<pattern> - Start a forward search for <pattern>.

?<pattern> - Start a reverse search for <pattern>.

Tutorial

Run vimtutor from the command line start the vim tutorial.

Emacs

Emacsis another powerful editor. Some people really find themselves drawn toviwhile others thoroughly enjoy usingemacs.It's a bit of a rivalry in the Linux world, actually. Experiment withemacsandvi to see which one works for you. You can't make a bad choice as they are both great editors.

emacs [file] - Edit file.

When readingemacs documentation,know thatC-<char>means to hold down theCtrl key while pressing <char>. For example,C-hmeans to hold down theCtrlkey while pressing thehkey. If you seeC-h t, that means to hold downCtrlkey while pressing thehkey, release theCtrlkey and then type the lettert.

When you seeM-<char>, that means hold down the "meta" key, which is theAlt key, while pressing <char>. You can also substitute theEsckey for theAltkey.M-ftranslates to holding down theAltkey and pressingfor pressing and releasingEscfollowed by typing thefkey. You may need to useEscfor the meta key sinceAltmay be intercepted by your terminal program, for instance. If you want to simplify things, always useEsc for the meta key as it will work in all situations.

Here are some helpfulemacs commands.

C-h - Help.

C-x C-c- Exit. While holding downCtrl, pressx, continue to hold downCtrl, and pressc.

C-x C-s - Save the file.

C-h t-Emacs has a nice built-in tutorial.

C-h k <key> - Describe key. Use this to get help on a specific key command or key combination.

Navigating

C-p - Previous line.

C-n - Next line.

C-b - Backward one character.

C-f - Forward one character.

M-f - Forward one word.

M-b - Backward one word.

C-a - Go to the beginning of the line.

C-e - Go to the end of the line.

M-< - Go to the beginning of the file.

M-> - Go to the end of the file.

Deleting Text

C-d - Delete a character.

M-d - Delete a word.

Copying and Pasting

C-k - Kill (cut) the rest of the current line of text. To kill the entire line, position the cursor at the beginning of the line.

C-y - Yank (or paste) from the previously killed text.

C-x u - Undo. Keep repeating for multi-level undo.

Searching

C-s- Start a forward search. Type the text you are looking for. PressC-sagain to move to the next occurrence. PressEnter when you are done searching.

C-r - Start a reverse search.

Repeating

Likevi, emacs provides a way to repeat a command.

C-u N <command>- Repeat <command>N times.

For instance, to kill three lines of text,typeCtrl-U 3 Ctrl-k.

You have only scratched the surface with theviandemacs editors. There is so much more to learn if you are interested. Both editors have features that include macros, global replace, and more. Entire books have been written on each of these editors.

Graphical Editors

So far, you have learned about command line editors that are appropriate to use when you connect to a server via ssh. However, if you are running Linux as a desktop operating system you might be interesting in some graphical text editors and word processors. Here are some for your consideration.

· emacs - Emacs has a graphical mode, too.

· gedit - The default text editor for the Gnome desktop environment.

· gvim- The graphical version ofvim.

· kedit - The default text editor for the KDE desktop environment.

If you are looking for a Microsoft Word replacement, consider AbiWord or LibreOffice. LibreOffice not only includes a word processor, but it is a complete office suite with a spreadsheet program, a database, and presentation software.

If you are looking for a source code editor to aid in computer programming, look at Geany, jEdit, or Kate. Sublime Text is another option. It is a commercial product that runs on Windows, Mac, and Linux.

Specifying a Default Editor

Some commands rely on the$EDITORenvironment variable to tell them which program to use for editing. Since cron's primary purpose is to schedule jobs, it delegates the task of editing files to another program. Thecrontab -ecommand invokes the editor specified by the$EDITORenvironment variable. You can set$EDITORin your personal initialization files to ensure your favorite editor is used, be itnano,emacs,vi, or something else.

$ echo $EDITOR

vi

Summary

In this chapter, you learned how to view and edit files. First you learned how to display the contents of a file using the cat, more, less, head, and tail commands. Next you learned how to use the nano text editor. From there you were introduced to the vim editor. Next, the emacs text editor was covered. Finally, graphical text editors were explained.

Quiz

1. Which of the following commands display the first line of the file named "file.txt"?

1. top file.txt

2. top +1 file.txt

3. head file.txt

4. head -1 file.txt

2. What command would you use to view the changes as they occur to the /var/log/messages file?

1. watch /var/log/messages

2. tail /var/log/messages

3. tail -f /var/log/messages

4. tail -1 /var/log/messages

3. Use the nano editor if you need powerful and complex editing capabilities.

1. True

2. False

4. Which is not a valid vi mode?

1. command

2. insert

3. line

4. fundamental

5. Emacs can be used as a graphical editor as well as from the command line.

1. True

2. False


Quiz Answers

1. D

2. C

3. B

4. D

5. A