/home/wpollock1/public_html/restricted/ShellScripting/pop1.txt
#!/bin/sh -
# Scripting project: An AWK program to print the population per square mile
# for a country in a specified continent, and when done print the total
# population of that continent. Note that the argument to this script
# is quoted in a strange-looking way, but it works. Also, the argument
# may be an arbitrary regular expression!
#
# The source data comes from $HOME/countrys.dat, whose format is:
# Country_Name Area Pop Continent
# The Area is in thousands of square miles, and the population is in
# millions of people.
#
# This script takes an argument: a regular expression for the contentent.
# (Try "pop1 America" and "pop1 .")
# The output is nicely formatted, showing commas in numbers, and the
# names of the continents used in the final total.
#
# Written by Wayne Pollock, Tampa Florida USA, 1997
# Updated 3/2015
cat $HOME/countrys.dat |awk '
BEGIN { FS = "\t" # Set the field separator to a tab.
continent = "'"$*"'"
if (continent == "")
continent = "Europe"
print ""
print " Country ", " People per"
printf " in %-6s %s\n", continent, " Square Mile"
print " ---------", " -------------"
}
$4 ~ continent { totalpop = totalpop + $3;
if (! search(names, $4))
names[cnt++] = $4
printf(" %-15s %10s\n", $1, fmt((1000 * $3) / $2) )
}
END { printf "\nTotal population of %s: ", list()
printf "%s million\n", ifmt(totalpop + 0)
}
function search (l, n, i) # Searches list l for name n
{ for (i=0; i<cnt; ++i)
if (l[i] == n)
return 1
return 0
}
function list (l, i) # build up a comma seperated list like: a, b, and c
{ if (cnt == 1)
return names[0]
else if (cnt == 2)
return names[0] " and " names[1]
l = names[0] ", and " names[1]
for (i = 2; i < cnt; ++i)
l = names[i] ", " l
return l
}
function fmt(num, fnum) # put commas into num (format dddd.ddd as d,ddd.dd)
{ if (num < 0)
return "-" fmt(-num)
fnum = sprintf("%.2f", num) # fnum is now dddd.dd
while (fnum ~ /[0-9][0-9][0-9][0-9]/)
sub(/[0-9][0-9][0-9][,.]/, ",&", fnum)
return fnum
}
function ifmt(num, fnum) # put commas into num (format dddd as d,ddd)
{
fnum = fmt(num + 0.5) # round num to nearest integer
sub(/\...$/, "", fnum) # strip the .dd from fnum
return fnum
}
' # End of awk program