Command Line Wizardry 2: Example.
So, after all that stuff I wrote a few minutes ago, I thought a real life example might be helpful. So here is something I wrote with a brief explanation.
#!/usr/local/bin/bash
grep 12.129.157.67 namedb/* | awk '{print $1}' | awk -F / '{print $2}' | awk -F ":" '{print $1}' | uniq > sites/w1.sites
grep 12.129.157.68 namedb/* | awk '{print $1}' | awk -F / '{print $2}' | awk -F ":" '{print $1}' | uniq > sites/w2.sites
grep 12.129.157.69 namedb/* | awk '{print $1}' | awk -F / '{print $2}' | awk -F ":" '{print $1}' | uniq > sites/w3.sites
grep 12.129.157.70 namedb/* | awk '{print $1}' | awk -F / '{print $2}' | awk -F ":" '{print $1}' | uniq > sites/w4.sites
grep 12.129.157.71 namedb/* | awk '{print $1}' | awk -F / '{print $2}' | awk -F ":" '{print $1}' | uniq > sites/w5.sites
grep 12.129.157.72 namedb/* | awk '{print $1}' | awk -F / '{print $2}' | awk -F ":" '{print $1}' | uniq > sites/w6.sites
grep 12.129.157.75 namedb/* | awk '{print $1}' | awk -F / '{print $2}' | awk -F ":" '{print $1}' | uniq > sites/loadbalanced.sites
What is all of this? Well, say you own a lot of domain names and websites and they are spread across numerous servers? What this does is checks the DNS entries and outputs the domain.com entry for each one based on IP address. So lets break one of these down.
grep 12.129.157.67 namedb/* | awk '{print $1}' | awk -F / '{print $2}' | awk -F ":" '{print $1}' | uniq > sites/w1.sites
First is grep. It searches all of the files in namedb/ for any lines matching 12.129.157.69 and outputs those lines to the console. Except, that there is a pipe so all of the output is fed into awk which simply prints out the first column of data. Which would look like this:
namedb/domain.com:www
I don’t care about that namedb part, so that output is piped into another awk comand. The -F says to basically separate columns of data on the / character that I specified. So then $1 is namedb and $2 is domain.com:www. So that awk command prints $2 and gives this:
domain.com:www
I don’t care about the www so the output is piped into a final awk command which uses -F : to say to split things up on the :. So if I print $1 that will give me:
domain.com
Finally! The output I’ve been looking for. Now I know that domain.com resides on whichever IP address. Since there are lots of domains and subdomains possible like www.domain.com or mail.domain.com, and I only want to know the base domain I pipe all of that input to uniq. Which only displays unique entries. So if before the uniq I had 30 domain.com’s listed, uniq will only give me one.
Then, I have > sites/w1.sites. That says to direct the output to the sites/w1.sites file. So I don’t get output, it is written to that file. So all I have to do is run that script, and I suddenly know where all of my domains reside.
February 12th, 2010, posted by rl










