Wednesday, November 21, 2007

Tail and Head Few Lines of Text Files

Another covered blog entry covering tail and heads. Tail and heads have been shown being use from several early blog entries here.

Here's a quick simple instructions on how to tail last or first few lines of a text file. This line can be an obsolete fancy phrase but if would look and read few more lines, the combination of the two can kick and produce a more useful data when used properly.

Here are several ways on how to tail last 10 lines of a text file.
# tail -10 testfile.txt
# tail -10 /var/log/maillog
# grep searchstring /var/log/maillog | tail -10
# cat longway.txt | tail -10

The same pattern goes on how to display the first 10 lines of a text file
# head -10 testfile.txt
# head -10 /var/log/maillog
# grep searchstring | head -10
# cat longway.txt | head -10

The numerical figure 10 can be replace by any non-decimal number.

Here are more samples of using tail and head linux commands to display several lines from textfile.

# tail -50 smallfile.txt
# tail -n50 largefile.txt
# head -50 test.txt
# head -n50 test.txt

This can be handy when creating linux shell scripts on gathering some data statistics from log files. Specifically, this can be helpful on determining a particular file, say a system logfile, on when did the first and last log file occurred from that particular log file, which can be a basis of a numerical value returned by a shell scripts.

There are more other ways to achieve the same effect using one or two linux command combinations.

Let's create a scenario where this two commands can be combined and produce a data useful to us.

# cat logfile.txt
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Nov 1 14:56:45 kiddos trying to hack the box
.
sniffed
.
.
.
.
.
Nov 21 4:56:45
Nov 21 6:26:22 kiddos trying to hack the box
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

From thousand log lines of logfile, and using the head and tail usage shown earlier, we could now conclude several things.

One of them is that there were 2 attempts that kiddos were trying to hack the box between the dates of Nov 1 and Nov 21. This number can also be compared from previous result we get from previous run of the script. Or even dump this number for MRTG to graph.

Most linux commands are really simple by usage, they get more useful and powerful when piped and combined from each other. Thus produce more interesting resulting data.

HTH

0 comments:

Sign up for PayPal and start accepting credit card payments instantly.
ILoveTux - howtos and news | About | Contact | TOS | Policy