Head, tail and split are three of the most commonly used utilities on GNU/Linux systems for the manipulation of text files. They are tiny, sharp, and all possess some handy options of which even the experienced user may be unaware.
Head returns the first lines of a file or standard input. By default, it outputs the first ten lines, but with the -n option it will return N lines.
Example: When did the syslog last roll over?
[root@sv-1 log]# head -n 1 /var/log/messages Jan 21 04:02:04 sv-1 syslogd 1.4.1: restart. |
With the -c option, you can output a number of bytes. Truthfully, dear reader, I’ve never found occassion to use the -c option. But I know it exists for a reason, so keep it in your bag of tricks.
We use tail constantly for following log files with the -f option. Even the most callow newbies know how to do that. But did you know that there are a couple of parameters pertaining to the -f option, which determine tail’s behavior when following a file that gets rolled over? The default behavior with tail -f is to continue tracking a file even once it’s been unlinked — overwritten or rolled over. For tailing syslog files on a console, use -F which will track the file by reopening it periodically. This prevents that stale end of a rolled over messages file on your console. Tail also takes the -c and -n options, exactly like head.
If only there were a way to combine the head and tail commands to extract someone’s head from … oh well. There’s not. I checked.
Split is a wonderful utility. It is great for dividing up data to distribute loads among servers. At every job, developers come to my desk to ask me how to use it. By default, split puts 1000 lines in each output file. But you can specify -l lines and -b bytes. The argument following the input file indicates the prefix for the output files. By default the prefix will be ‘x’, and the suffixes will be aa, ab, and so on.
Example: Divide a data file into three roughly equal chunks for loading.
[root@sv-1 test]# wc -l zdata 4936 zdata [root@sv-1 test]# split -l 1700 zdata zdata [root@sv-1 test]# ls -l total 532 -rw------- 1 root root 260718 Jan 24 17:58 zdata -rw-r--r-- 1 root root 90940 Jan 24 18:00 zdataaa -rw-r--r-- 1 root root 88400 Jan 24 18:00 zdataab -rw-r--r-- 1 root root 81378 Jan 24 18:00 zdataac |
So whether you want to cut off a head, chop off a tail, or hack something up into pieces, there’s a sharp little knife in the GNU/Linux toolbox for each task.