The awk Passes parameters to the script (2). The awk script Passes parameters.
An important limitation of command line parameters is that they are unavailable during the in process. That is, they are available only after the first line is entered. Why? This is a confusing part. Parameters passed from the command line are processed like file names. The value assignment operation is performed only when the variable (if it is a file name) is evaluated.
Refer to the following script to set Variable n as a command line parameter.
Awk 'in in {print n}
If (n = 1) print "Reading the first file"
If (n = 2) print "Reading the second file"
} 'N' = 1 test n = 2 test2
There are four command line parameters: "n = 1", "test", "n = 2", and "test2 ". If you still remember the BEGIN process as "what to do before processing Input", you will understand why the return value of parameter n in the BEGIN process is null, therefore, the print statement prints an empty line. If the first parameter is a file rather than a variable value. This file will be opened only after the BEGIN process is executed.
The first parameter is Variable n assigned initial value 1, and the second parameter provides the file name. Therefore, for each row in test, the condition "n = 1" is true. After reading all the rows in test, calculate the third parameter and assign n to 2. Finally, the fourth parameter provides the second file name. In this case, the condition "n = 2" in the main process is true.
The consequence of using this method to evaluate parameters is that you cannot use the BEGIN process to test or test the parameters provided by the command line. They can be used only when a row is entered. To understand this limitation, You can compile the rule "NR = 1" and use its procedure to test the parameter assignment. Another method is to test the command line parameters in shell scripts before calling awk.
POSIX awk provides a solution to this problem, that is, defining parameters before any input is read. Use the-v option to specify that the variable value should be obtained before the BEGIN process is executed (that is, before the first input line is read ). The-v option must be described before a command line script. For example, the following command uses the-v option to set the record delimiter for multiple line records.
$ Awk-F' \ n "-v RS =" "'{print}' phones. block
Each variable assigned to a program requires a different-v option.
Like C programming languages, awk also provides system variables ARGC and ARGV. Because this requires an understanding of arrays, we will discuss these features in "conditions, loops, and arrays.
Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.