AWK - Assignment Operators


Advertisements

AWK supports the following assignment operators −

Simple Assignment

It is represented by =. The following example demonstrates this −

Example

[jerry]$ awk 'BEGIN { name = "Jerry"; print "My name is", name }'

On executing this code, you get the following result −

Output

My name is Jerry

Shorthand Addition

It is represented by +=. The following example demonstrates this −

Example

[jerry]$ awk 'BEGIN { cnt = 10; cnt += 10; print "Counter =", cnt }'

On executing this code, you get the following result −

Output

Counter = 20

In the above example, the first statement assigns value 10 to the variable cnt. In the next statement, the shorthand operator increments its value by 10.

Shorthand Subtraction

It is represented by -=. The following example demonstrates this −

Example

[jerry]$ awk 'BEGIN { cnt = 100; cnt -= 10; print "Counter =", cnt }'

On executing this code, you get the following result −

Output

Counter = 90

In the above example, the first statement assigns value 100 to the variable cnt. In the next statement, the shorthand operator decrements its value by 10.

Shorthand Multiplication

It is represented by *=. The following example demonstrates this −

Example

[jerry]$ awk 'BEGIN { cnt = 10; cnt *= 10; print "Counter =", cnt }'

On executing this code, you get the following result −

Output

Counter = 100

In the above example, the first statement assigns value 10 to the variable cnt. In the next statement, the shorthand operator multiplies its value by 10.

Shorthand Division

It is represented by /=. The following example demonstrates this −

Example

[jerry]$ awk 'BEGIN { cnt = 100; cnt /= 5; print "Counter =", cnt }'

On executing this code, you get the following result −

Output

Counter = 20

In the above example, the first statement assigns value 100 to the variable cnt. In the next statement, the shorthand operator divides it by 5.

Shorthand Modulo

It is represented by %=. The following example demonstrates this −

Example

[jerry]$ awk 'BEGIN { cnt = 100; cnt %= 8; print "Counter =", cnt }'

On executing this code, you get the following result −

Output

Counter = 4

Shorthand Exponential

It is represented by ^=. The following example demonstrates this −

Example

[jerry]$ awk 'BEGIN { cnt = 2; cnt ^= 4; print "Counter =", cnt }'

On executing this code, you get the following result −

Output

Counter = 16

The above example raises the value of cnt by 4.

Shorthand Exponential

It is represented by **=. The following example demonstrates this −

Example

[jerry]$ awk 'BEGIN { cnt = 2; cnt **= 4; print "Counter =", cnt }'

On executing this code, you get the following result −

Output

Counter = 16

This example also raises the value of cnt by 4.

awk_operators.htm
Advertisements