Work with File Content
This chapter is all about file content and what you can do with it from the Unix command line. The nine projects cover the following topics:
- View text files. Learn how to display text files page by page and view them dynamically as they are being written.
- View nontext files. View binary and compressed files.
- Search files. Say hello to grep and friends—the Unix equivalent of Spotlight.
- Sort and compare files. Unix has some handy utilities to process text files.
- Compress files. Discover tar-balls for archiving, and learn how to zip and unzip.
These projects show you how to search the file system for specific content, view files, process them, and compress them. For related projects, see Chapter 4 on Unix text editors, and Chapter 7, which shows how to change file content programmatically.
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.
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.
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.
$ 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 file—handy 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.
$ 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.
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
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
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 match—handy 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.
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.
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 rewritten—changed 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.
The Console Application
The Console application in Applications:Utilities:Console.app is the OS X-native equivalent of tail -f.