AWK - Increment and Decrement Operators


Advertisements

AWK supports the following increment and decrement operators −

Pre-Increment

It is represented by ++. It increments the value of an operand by 1. This operator first increments the value of the operand, then returns the incremented value. For instance, in the following example, this operator sets the value of both the operands, a and b, to 11.

Example

awk 'BEGIN { a = 10; b = ++a; printf "a = %d, b = %d\n", a, b }'

On executing this code, you get the following result −

Output

a = 11, b = 11

Pre-Decrement

It is represented by --. It decrements the value of an operand by 1. This operator first decrements the value of the operand, then returns the decremented value. For instance, in the following example, this operator sets the value of both the operands, a and b, to 9.

Example

[jerry]$ awk 'BEGIN { a = 10; b = --a; printf "a = %d, b = %d\n", a, b }'

On executing the above code, you get the following result −

Output

a = 9, b = 9

Post-Increment

It is represented by ++. It increments the value of an operand by 1. This operator first returns the value of the operand, then it increments its value. For instance, the following code sets the value of operand a to 11 and b to 10.

Example

[jerry]$ awk 'BEGIN { a = 10; b = a++; printf "a = %d, b = %d\n", a, b }'

On executing this code, you get the following result −

Output

a = 11, b = 10

Post-Decrement

It is represented by --. It decrements the value of an operand by 1. This operator first returns the value of the operand, then it decrements its value. For instance, the following code sets the value of the operand a to 9 and b to 10.

Example

[jerry]$ awk 'BEGIN { a = 10; b = a--; printf "a = %d, b = %d\n", a, b }'

On executing this code, you get the following result −

Output

a = 9, b = 10
awk_operators.htm
Advertisements