Saturday, 20 August 2011

Head And Tail

head is a program on Unix and Unix-like systems used to display the first few lines of a text file or piped data. The command syntax is:

head [options] <file_name>
By default, head will print the first 10 lines of its input to the standard output. The number of lines printed may be changed with a command line option.

The following example shows the first 20 lines of filename:
head -n 20 filename 
This displays the first 5 lines of all files starting with foo:
head -n 5 foo* 
 
Tail Command 
tail [options] <file_name>

By default, tail will print the last 10 lines of its input to the standard output. With command line options the number of lines printed and the printing units (lines, blocks or bytes) may be changed. The

following example shows the last 20 lines of filename:
tail -n 20 filename
This example shows the last 15 bytes of all files starting with foo:
tail -c 15 foo*
This example shows all lines of filename from the second line onwards:
tail -n +2 filename

File monitoring

tail has a special command line option -f (follow) that allows a file to be monitored. Instead of just displaying the last few lines and exiting, tail displays the lines and then monitors the file. As new lines are added to the file by another process, tail updates the display. This is particularly useful for monitoring log files. The following command will display the last 10 lines of messages and append new lines to the display as new lines are added to messages:

tail -f /var/adm/messages 
In cases when the user is following a log file that rotates then it  is advisable to use the -F option as it keeps folllowing the log even  when it is recreated, renamed, or removed as part of log rotation.

tail -F /var/adm/messages 
To interrupt tail while it is monitoring, break-in with Ctrl+C. This command can be run "in the background" with &,
 

No comments:

Post a Comment