A common way awk scripts are written is to use top-level pattern-action blocks. The file would then consist of multiple top-level pattern-action blocks. Each block would apply to input lines matching its pattern. This works well for simple operations intended for a single purpose.
I would like my awk files to have the capability of performing more than a single specific operation on the data.
Have found that to perform different operations conditionally or modularly, top-level blocks alone become unwieldy.
Using functions with a mode variable for each operation I want to perform can be used to select which function to call for each input line. Which lets me write a single main block that dispatches processing based on the mode.
function operation1(line) {
# code for operation 1
}
function operation2(line) {
# code for operation 2
}
{
if (mode == "op1") {
operation1($0)
} else if (mode == "op2") {
operation2($0)
} else {
# default action
print $0
}
}
I then pass the mode variable from the command line:
awk -v mode=op1 -f script.awk inputfile
Is this the way to accomplish what I want.? Are there other ways that can be utilised.used?