View The First or Last few lines of a file

First Few Lines

Use the Unix head command to read the first few lines of an input file and send them to standard output (i.e., your terminal screen). The format for the head command is:

head -lines filename 

In this example, lines is an optional value specifying the number of lines to be read. If you don't give a number, the default value of 10 is used. Also, filename represents the name of an optional file for the head command to read. Otherwise, it will take its input from stdin (standard input: the terminal, or whatever the shell feeds the process with, usually pipe output).

For example, given a file containing the English alphabet with each letter on a separate line, a user enters the command:

head -3 alphabetfile 

This command would return:

a
b
c 

You can also use the head command with pipes. For example, to see the sizes of the first few files in a large directory, you could enter at the Unix prompt:

ls -l | head 

To save this information into a file in the current directory named mylist, you could enter:

ls -l | head > mylist 

For more information, consult the Unix manual page by entering at the Unix prompt:

man head

Last Few Lines

Use the Unix command tail to read from standard input or a file and send the result to standard output (i.e., your terminal screen). The format for using the tail command is:

tail [ +-[number][lbcr] ] [file] 

Everything in brackets is an optional argument. If you don't specify a filename, tail uses standard input.

Tail begins at distance +number from the beginning or -number from the end of the input. The number is counted in units of lines, blocks, or characters, according to the appended options -l, -b, or -c. When you don't specify a unit, tail operates based on lines.

Specifying -r causes tail to print lines from the end of the file in reverse order. The default for -r is to print the entire file this way. Specifying -f causes tail not to quit at the end of the file, but rather to reread the file repeatedly (useful for watching a “growing” file such as a log file).

For example, given a file containing the English alphabet with each letter on a separate line, the command:

tail -3 alphabetfile 

would report:

x
y
z 

You can use tail with pipes. For example, to see the sizes of the last few files in the current directory, you could enter at the Unix prompt:

ls -l | tail 

To save this information in a file in the current directory named mylist, at the Unix prompt, enter:

ls -l | tail > mylist 

For more detailed information on tail, consult the Unix manual page by entering at the prompt:

man tail

kb/linux/viewfirstorlastlines.txt · Last modified: 2007/08/06 13:45 by akuelbs