Skip to main content

Command Palette

Search for a command to run...

awk command

Published
2 min readView as Markdown
awk command
X

"I am currently a Software Engineering student at ALX. I'm passionate about technology and enjoy conducting research to find answers on my own. I have a natural inclination to ask 'WHY' more often than 'HOW'.

"While working on projects at ALX, I have acquired a wealth of interesting and diverse knowledge about software engineering and computer science in general. Therefore, I needed a place to store and save all this information, allowing me to refer back to it whenever I forget."

write a Bash script that groups visitors by IP and HTTP status code, and displays this data.

Requirements:

  • The exact format must be:

    • OCCURENCE_NUMBER IP HTTP_CODE

    • In list format

  • Ordered from the greatest to the lowest number of occurrences

    • See example
  • You must use awk

awk '{ print $1,$9 }' apache-access.log | sort | uniq -c | sort -nr

Link to download apache.log file

Let's break down the command step by step using a simplified example:

Consider the following sample data:

192.168.1.1 200
192.168.1.2 404
192.168.1.1 200
192.168.1.3 500
192.168.1.2 200
  1. awk '{ print $1,$2 }' apache-access.log: This awk command extracts the first and second fields (IP address and HTTP status code) from each line of the apache-access.log file and prints them. Here's the output:
192.168.1.1 200
192.168.1.2 404
192.168.1.1 200
192.168.1.3 500
192.168.1.2 200
  1. sort: This sort command sorts the output in ascending order:
192.168.1.1 200
192.168.1.1 200
192.168.1.2 200
192.168.1.2 404
192.168.1.3 500
  1. uniq -c: This uniq command filters adjacent matching lines and displays them with a count of their occurrences:
   2 192.168.1.1 200
   1 192.168.1.2 200
   1 192.168.1.2 404
   1 192.168.1.3 500

The count represents the number of occurrences of each unique combination of IP address and HTTP status code.

  1. sort -nr: This sort command sorts the output numerically in descending order:
   2 192.168.1.1 200
   1 192.168.1.3 500
   1 192.168.1.2 404
   1 192.168.1.2 200

The result is a sorted list where each line shows the count followed by the unique combination of IP address and HTTP status code.

By applying this command sequence to your apache-access.log file, you'll get a similar output, which can be helpful for analyzing the frequency of IP addresses and their associated HTTP status codes in the log file.

More from this blog

PERSONAL BLOG

110 posts

Use the search button to search for a specific topic or keyword *all posts are updated on the go*