Perl Script to Parse Log File

Problem

You have a log file on UNIX operating system. Each line in the log file contains an IP address in the 10th column where columns (or fields) are separated by a space. Write a Perl program to parse the log file and print the unique IP addresses in the log file

Solution

Read the file line by line then split the current line into an array of tokens using space as separator. Push the 10th token into a result array. To print the unique IP addresses in the result array I will suggest two methods. You can sort the array which is O(nlogn) operation then you go through the sorted array element by element while printing the current element as long as it is different from the previously printed element.

Code

Here is the code in Perl

Solution

The other way is to hash the IP addresses where the key is the IP itself and the value is the count. Once the hash table is fully populated you go through the hash and print the keys

Code

Here is the code in Perl

Add a Comment

Your email address will not be published. Required fields are marked *