7.4.5 The switch
Statement
This section describes a gawk
-specific feature.
The switch
statement allows the evaluation of an expression and the execution of statements based on a case
match. Case statements are checked for a match in the order they are defined. If no suitablecase
is found, the default
section is executed, if supplied.
Each case
contains a single constant, be it numeric, string, or regexp. The switch
expression is evaluated, and then eachcase
’s constant is compared against the result in turn. The type of constant determines the comparison: numeric or string do the usual comparisons. A regexp constant does a regular expression match against the string value of the original expression. The general form of the switch
statement looks like this:
switch (expression) { case value or regular expression: case-body default: default-body }
Control flow in the switch
statement works as it does in C. Once a match to a given case is made, the case statement bodies execute until a break
,continue
, next
, nextfile
or exit
is encountered, or the end of the switch
statement itself. For example:
switch (NR * 2 + 1) {
case 3:
case "11":
print NR - 1
break
case /2[[:digit:]]+/:
print NR
default:
print NR + 1
case -1:
print NR * -1
}
Note that if none of the statements specified above halt execution of a matched case
statement, execution falls through to the next case
until execution halts. In the above example, for any case value starting with ‘2’ followed by one or more digits, the print
statement is executed and then falls through into thedefault
section, executing its print
statement. In turn, the -1 case will also be executed since the default
does not halt execution.
This switch
statement is a gawk
extension. If gawk
is in compatibility mode (see Options), it is not available.
'Programming > Script' 카테고리의 다른 글
GETOPTS (0) | 2023.04.17 |
---|---|
[awk] awk 연습 예제 (0) | 2014.08.28 |
[awk] Time Functions (0) | 2014.08.28 |
[awk] gawk - Date and time calculation functions (0) | 2014.08.28 |
[awk] The GNU Awk User's Guide (0) | 2014.08.28 |
[awk] The AWK Manual (0) | 2014.08.28 |
[RHEL] SU와 EOF 사용시 내부 변수 처리 (0) | 2014.05.07 |
awk 패턴 이용하기 (0) | 2014.05.07 |
쉘스크립트 컴파일러 shc (0) | 2014.01.29 |
[OS] Awk - A Tutorial & Introduction (Bruce Barnett) (0) | 2009.01.12 |