Archive for December, 2006

Viewing text files: cat, head, tail, more, less

If you're new here, you may want to subscribe to my RSS feed.

Many Unix files are text files. This may seem simplistic, but it’s actually very powerful. Text files are easy to create, read, and manipulate. Many Unix commands are for working with text files.

The first category of Unix commands for working with text files might be called “text viewers”. These includes commands such as cat, head, tail, more, and less. All of these commands are used by typing the command plus the name of a file.

cat — Short for “concatenate”, this command is used to temporarily combine files. But if you use it on only one file, it just displays the file to the screen.

head — This command shows the first 10 lines of a file. (You can adjust the number of lines using the flag -n.)

tail — This command shows the last 10 lines of a file. (You can also use -n here to show more lines.)

more — Like cat, this shows the entire contents of a file, but prompts you for “more?” between each page. Hit the space bar to go to the next page, or use the up and down arrows. Hit “q” to quit.

less — This is another “pager” like more, i.e. it shows one page at a time. It was meant to be a successor or alternative to more and was hence given the opposite name less. It had more features than more (sounds like an Abbott and Costello routine) when it first came out, but now the two commands are about the same.

Here are some examples:

How to view your hosts file, where you can map host names to IP addresses:
cat /etc/hosts

If you have Personal Web Sharing turned on, how to view the last 10 lines of the Apache log file:
tail /var/log/httpd/access_log

How to read the Apache configuration file, one page at a time:
more /etc/httpd/httpd.conf

Invisible files

Files that begin with a dot . are invisible to Mac OS X. They’re also not typically shown in Unix, but it’s easy to change that. For example, if you open Terminal and type ls you’ll see Desktop, Documents, etc. But if you type ls -a you’ll also see additional hidden files that begin with a dot.

The dot is useful for hiding configuration files that might otherwise clutter your view. On a web server like Apache, files beginning with a dot can’t be accessed over the web. That’s why you can safely put configuration options for each directory in an .htaccess file. (If you have a web site, you’ve almost certainly seen .htaccess files.)

In addition to the Unix method of hiding files by beginning them with a dot, Mac OS X also includes its own unique way of hiding files and folders. If you install the Developer Tools CD that came with your Mac, you’ll have access to a SetFile command. You can type SetFile -aV and the name of a file to make the file invisible. You can use SetFile -av (lowercase “v”) to make the file visible again.

In addition, you can see ALL the files on a computer by using Applications like Smultron that have an “Open Hidden” option.