awktutorial/07-flow-control.awk

77 lines
2.6 KiB
Awk
Executable File

#!/usr/bin/awk -f
# https://www.grymoire.com/Unix/Awk.html
# user input, loops and flow control
# this example takes a few simple concepts and ties them
# together in a single demo
# 1. you can take user input in a script with the getline function
# like this:
# prompt "What is your name?"
# getline name < "-"
# print "Hello " name "!"
# 2. awk has flow control structures, that can be used in the following
# forms:
# for (var in array) { do something; }
# for (var=start_val; var>=end_val; var++) { do something; }
# while (var >= val) { do something; }
# do {do something} while (var >= val)
# switch (var) { case value/regexp: ...; default: ...; } [* see below]
# and the loops can be controlled with the following operators:
# break - exit the loop and continue with the rest of the program.
# continue = skip the rest of the current loop iteration, start next iteration.
# next = stop processing this record (not just loop), and move to next record.
# exit - exit the entire program, not just the loop.
# note that continue and next may be confusing because the nature of awk is that
# it loops over records. but next refers to the structural awk loop while
# continue refers to loops within the program that you have created in a for,
# while or do structure.
BEGIN {
print "This program will count how many times you type different fruit names."
fruit_count[""] = ""
while (1) {
print "Enter a fruit name, or type 'q' to quit."
getline fruit < "-"
if (fruit == "") {
print "You didn't enter a fruit name. Try again."
continue
} else if (fruit == "q" || fruit == "Q") {
exit
} else if (fruit == "done" || fruit == "DONE" || fruit == "Done") {
break
} else {
fruit_count[fruit]++
}
}
for (f in fruit_count) {
print f, fruit_count[f]
}
}
# in this example, we used the continue, break and exit within a while loop.
# this could have also used a for loop or a do loop in the BEGIN block.
# a more common form of flow control might be to use the 'next' statment in
# the main program block. as stated above, 'next' causes processing of the
# current line of input to stop and awk to read in the next line of input for
# processing.
# * the structure of the switch statement is like this:
# switch (expression) {
# case value or regular expression:
# case-body
# default:
# default-body
# }
# you can read more about the switch structure here:
# https://www.gnu.org/software/gawk/manual/html_node/Switch-Statement.html#Switch-Statement