Publishers of technology books, eBooks, and videos for creative people

Home > Articles

Work with File Content

This chapter is from the book

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.

Peachpit Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from Peachpit and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about Peachpit products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites; develop new products and services; conduct educational research; and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email ask@peachpit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by Adobe Press. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.peachpit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020