Introducing UNIX and Linux |
AwkOverview |
FunctionsJust as Worked exampleWrite a script to 'roll a die'. Each time a line of input is
entered, the script should display a number between 1 and 6 to
mimic someone throwing a die. awk '{ printf "%d\n", int(rand()*6 + 1) }' The trigonometric functions use radians, not degrees, and the
number returned by Worked exampleWrite a shell script to read the password file and display each
user's name in capitals. awk ' BEGIN { FS=":" } { print toupper($5) }' < /etc/passwd Where a function takes a string as argument, that string is not
itself altered, so that if you passed Worked exampleA certain Birmingham electrical retail company offers free
delivery of its products to customers living in the Birmingham
area, defined as having addresses with postcode commencing
invoice number,customer,road,town,postcode For example, 6152,J. Smith,1 High St.,Birmingham,B99 9ZZ 6183,F. Bloggs,5 Long Ave.,Dudley,DY1 1AA The company requires a document to instruct the delivery driver
whom to visit and whom to collect a delivery fee from. ^B[0-9] namely a # Set the field separator to be a comma BEGIN { FS="," } # For each line, $5 is the postcode # Check if it is a Birmingham one { if ( match($5, "^B[0-9]") > 0) fee = "no fee" else fee = "standard fee" # Print out message for driver printf "%s, %s, %s, %s: %s\n", $2, $3, $4, $5, fee } |
Copyright © 2002 Mike Joy, Stephen Jarvis and Michael Luck