Once a variable is given a value, it can be referenced with the variable name. The following expression represents the addition of the value of the variable x and 1 and assigns the result to the variable y:
Y=X+ 1
That is, the value of x plus 1 is computed and the result is assigned to the variable Y. Statement
Print Y
Prints the value of Y. If the following series of statements will appear in the script:
X=1
Y=X+1
Print Y
Then the value of Y is 2.
We can reduce these 3 statements to two:
X= 1
Print X+1
assignment operator
operator
definition |
++ |
variable plus 1 |
-- |
variable minus 1 |
+= |
Assign the result of the addition to the variable |
-= |
Assigns the result of the subtraction to the variable |
*= |
Assigns the result of the multiply to the variable |
/+ |
Assign the result of the addition to the variable |
%= |
Assign the result of the modulo to the variable |
^= |
Assigns the result of the exponentiation to the variable |
**= |
Assigns the result of the exponentiation to the variable |
The following example is used to calculate a directory of empty rows in a file.
#统计空行数
/^$/{Print X+=1}
Although there is no initial value assigned to variable x here. But it has a value of 0 until the first empty row is encountered. The expression x+=1 evaluates and increments the value of X by 1 each time a blank row is encountered. The print statement prints the value returned by the expression. Because we execute the PRINT statement when we encounter every empty row, we get a continuous value for the number of empty rows.
Expressions can be expressed in different forms and somewhat more concise. The expression x+=1 than the equivalent expression: x=x+1 is more concise. But neither of these two are as concise as the following expression:
++X
"+ +" is the increment operator ("--" is the decrement operator). An expression increases by 1 for each time the value of the variable is evaluated. The increment and decrement operators can appear on either side of the operand, where different results can be computed.
++x increment the value of x (prefix) before returning the result
X + + increments the value of x. (suffix) after returning the result
Reference: http://www.linuxawk.com/communication/480.html
awk assignment operator