Chapter 4. Head Aches
Stand on your own head for a change / Give me some skin to call my own
They Might Be Giants, “Stand on Your Own Head” (1988)
The challenge in this chapter is to implement the head program, which will print the first few lines or bytes of one or more files.
This is a good way to peek at the contents of a regular text file and is often a much better choice than cat.
When faced with a directory of something like output files from some process, using head can help you quickly scan for potential problems.
It’s particularly useful when dealing with extremely large files, as it will only read the first few bytes or lines of a file (as opposed to cat, which will always read the entire file).
In this chapter, you will learn how to do the following:
-
Create optional command-line arguments that accept numeric values
-
Convert between types using
as -
Use
takeon an iterator or a filehandle -
Preserve line endings while reading a filehandle
-
Read bytes versus characters from a filehandle
-
Use the turbofish operator
How head Works
I’ll start with an overview of head so you know what’s expected of your program.
There are many implementations of the original AT&T Unix operating system, such as Berkeley Standard Distribution (BSD), SunOS/Solaris, HP-UX, and Linux.
Most of these operating systems have some version of a head program that will default to showing the first 10 lines of 1 or more files.
Most will probably have options -n to control the number of lines ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access