Project21.Display Text Files


Project 21. Display Text Files

"How do I view a file quickly?"

This project introduces commands to display the contents of a file in the Terminal window and to browse quickly through it. It covers cat, vis and unvis, less, head, and tail.

Tip

Create a short text file quickly and easily by using cat and redirection. Type the text you want to be in the file, and, when you've finished, press Control-d (interpreted as end of input).

$ cat > letter.txt Dear Janet, How are you these days? <Control-d>



Reading Files with cat and vis

The simplest way to display a file on the screen is to cat it. Let's illustrate this by displaying one of the system files called /etc/ftpusers.

$ cat /etc/ftpusers # list of users disallowed any ftp access. # read by ftpd(8). Administrator administrator root uucp daemon unknown www


The cat command pours the whole file onto the screen in one go. If the file is too big, it will overflow the Terminal window, leaving only the tail end visible. The name cat is short for concatenate and was originally written to join many files sequentially to form one large file. For example:

$ cat part1 part2 part3 > all-parts


The cat command has a few useful options. Option -n displays line numbers.

$ cat -n letter.txt      1  Dear Janet,      2  How are you these days?


Option -s squeezes multiple blank lines into a single blank line, while option -v displays nonprinting characters visibly. A file containing control characters can look a mess when displayed on the screen; worse, it can put the terminal into a peculiar mode.

Tip

If the terminal suddenly starts spitting out weird-looking characters, try resetting it by typing reset or tput reset.


Command vis provides a better way of dealing with control characters, being written specifically to display nonvisible characters. To illustrate, let's display a file that contains four control characters: Control-a, Control-b, Control-c, and Control-d.

Tip

To view the ASCII character set, including all control and other nonvisible characters, type

$ man ascii



$ vis control Here are four control characters: \^A\^B\^C\^D


The output generated by vis has each nonvisible character represented by a unique sequence of visible characters. Because the sequences are unique, this human-readable output can be turned back into its original binary form. The unvis command does just this, taking the output from vis and restoring the original filehandy when you need to process or transmit a file in which control characters might cause problems. We might redirect the output from vis to the file safe, which is transmitted and then used as the input to unvis, thereby re-creating the original file contents.

Learn More

Project 22 shows you how to view binary files and compressed files.


$ vis control > safe $ # and sometime later $ unvis safe > control


Use the cat command as a simple filter to tidy up a messy file. We can remove unnecessary blank lines from a file by using the following commands.

$ cat -s messy.txt > tmp $ mv tmp messy.txt


Note that this places the cleaned-up contents of messy.txt in a new file called tmp, and then replaces the original file by renaming tmp to messy.txt. As discussed in Project 6, trying to redirect output back into the original input file can trash the file or cause an infinite loop.

Make a Hard Copy

Printing is beyond the scope of this book, but it's worth mentioning a few key commands. The lp command sends a document to the printer, using CUPS (Common Unix Printing System, a resource built into OS X since version 10.3) to handle print jobs.

Learn More

Chapter 4 introduces Unix text editors.



The pr command formats pages before they are printed, adding a timestamp header to the top of each page. Option -l sets the number of lines per page, and option -F ensures that multi-page documents print correctly. Pipe the output from pr to lp to print the formatted document.

$ pr -l57 -F ~/Sites/deq/php-lib/db/Deq.php | lp


Tip

man uses the less command to display man pages, and it's such a useful command that it's worthwhile getting to know well.


The less Pager

Type less followed by a filename to displays the file's contents one page at a time. The less command is not an editor; it will only display files.

$ less Sites/index.html


The less command provides a very quick way of flicking through a file. It doesn't wait for the entire file to load before displaying the first page, so it's faster than using an editor to view a file. You can page through the file by pressing the spacebar. Search for a specific pattern by typing /pattern and then pressing Return. Press n to move to the next occurrence of the pattern and N to move to the previous occurrence. Press q to quit less. Read the man page for less: It has many options and navigation keystrokes, and will take some reading. To save you time, the most useful features are summarized below.

Navigation

Use the following keystrokes to move forward and backward through the file:

  • space and b to move forward and back a page at a time

  • d and u to move down and up a half-page

  • Down arrow and up arrow to move forward and back a line at a time

  • Right arrow and left arrow to scroll horizontally

  • ng to move to line number n (for example, type 11g to go to line 11)

  • g and G to move to the beginning and end of the file

  • n% to move n% of the way through the file

  • /pattern Return to search forward for lines containing a pattern

  • ?pattern Return to search backward for lines containing a pattern

  • n and N to search for the next and previous occurrences of a pattern

  • :e filename to examine (view) another file

  • :n and :p to view the next and previous file when less is given more than one file to view (like less *.txt)

  • Control-g to display a status line

  • R to repaint (handy if the file being viewed is changing)

  • h to display a help screen

  • q to quit less

Tip

The less command can use regular expressions in search patterns. Project 77 shows you how to use regular expressions.


Options

Here are some of the more useful options:

  • -a causes a search to resume from the last line displayed, rather than from the last matchhandy when a single page shows many matches.

  • -i causes less to ignore case when searching for strings unless the search pattern contains uppercase characters. So /hello matches hello and Hello, but /Hello matches only Hello.

  • -M says to display a long prompt on the last line. The prompt can be customized; see the man page for less and search for ^PROMPTS to find the relevant section.

  • -N displays a line number preceding each line of the file.

  • -Q says shhhh! and stops less from ever dinging that annoying terminal bell.

Specify options to less in one of three ways:

  • On the command line as usual.

  • Interactively while viewing a file. S imply type an option like -a to toggle it on and off.

  • In the environment variable LESS. When less is invoked, it assumes that the options listed in the environment variable LESS were actually passed on the command line.

Tip

Set the following environment variables to enhance less. (See "Bash Initialization" in Project 4 to learn how to make them stick across shell sessions.)

For less invoked on the command line in the normal manner:

declare -x LESS="-aiMq"


For less invoked via the man command to display man pages:

declare -x PAGER= "less -aiMqRs"



Use Bookmarks

Set a bookmark so you can flip to the marked point in the file at any time. To set a mark, type m followed immediately by any lowercase letter from a to z. (You can have as many as 26 bookmarks per file). To return to a mark from elsewhere in the file, type ' (the single-quote character) followed immediately by the bookmark letter. Type '' (two single quotes) to flip between the last two bookmarks.

Tip

The navigation keystrokes and commands understood by less are similar to those understood by the vi and vim text editors. Projects 32 to 34 cover vi and vim.


more or less

A Unix pager called more was a forerunner of less. It doesn't have half the features of less and cannot move backward when viewing a file. Unix under Mac OS X recognizes command more, but all it does is invoke less. So remember, more is less, less is more than more, and more is less than less!

heads or tails

Command head displays the first 10 lines of a file. Specify option -n followed by a number to display a different number of lines. To display the first five lines of the file index.html, we would type

$ head -n5 ~/Sites/index.html


Command tail displays the last 10 lines of a file. Specify option -n followed by a number to display a different number of lines. To display the last few events in the system log file, we would type

$ tail -n5 /var/log/system.log May 25 08:55:00 saruman CRON[14842]: (root) CMD (/usr/l... May 25 09:00:00 saruman CRON[14844]: (root) CMD (/usr/l... May 25 09:05:00 saruman CRON[14847]: (root) CMD (/usr/l... May 25 09:05:04 saruman xinetd[323]: START: pop3s pid=1... May 25 09:10:00 saruman CRON[14852]: (root) CMD (/usr/l...


View Live Files

The tail command has a few options, the most useful of which, -f and F, let you monitor continual changes to a file's contents. Use option -f to track files that are continually extended by the addition of appended text. Use option -F to track files as they are rewrittenchanged in a text editor or replaced with an updated file that takes its name.

A system log file is a good candidate for tail's -f option. Whenever a line of text is appended to the file, tail displays the new line:

$ tail -f -n3 /var/log/system.log May 25 09:10:00 saruman CRON[14852]: (root) CMD (/usr/l... May 25 09:13:44 saruman xinetd[323]: START: pop3s pid=1... May 25 09:15:00 saruman CRON[14871]: (root) CMD (/usr/l... # then a little later May 25 09:17:54 saruman sudo: saruman : TTY=ttyp5 ;PWD...


Press Control-c to quit tail.

Changing or Rewriting?

When a file is changed, its i-node number remains the same. When a file is rewritten, a new file is created, and its i-node number changes; this is when tail requires option -F. Use the command ls -i filename to examine the i-node number of a file.

An i-node is an intermediary between the directory entry for a file and the file itself. The directory entry mentions the i-node number, and the i-node points to the location of the file on disk. A new file means a new i-node number.

The concept of i-nodes is explored in greater depth in Project 19.


The Console Application

The Console application in Applications:Utilities:Console.app is the OS X-native equivalent of tail -f.




Mac OS X UNIX 101 Byte-Sized Projects
Mac OS X Unix 101 Byte-Sized Projects
ISBN: 0321374118
EAN: 2147483647
Year: 2003
Pages: 153
Authors: Adrian Mayo

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net