awk(2) Instructions in awk

awk的指令:
expression ( function calls, assignments..)
print expression-list
printf( format, expression-list)
if( expression ) statement [else statement]
while( expression ) statement
do statement while( expression)
for( expression; expression; expression) statement
for( variable in array) statement
delete
break
continue
next
exit [expression]
statement


示例:
1)、if...else...
awk脚本
awk 'BEGIN{
    num=ARGV[1]
    if(num>3){
        print "num larget 3"
    }else if(num<3){
        print "num less 3"
    }else{
        print "num eq 3"
    }
}' $*


2), while
example: decrement output
awk '
BEGIN{
    num=ARGV[1]
    while(num>0){
        print num
        num--
    }
}
' $* 


3), do...while
example: decrement output
awk '
BEGIN{
    num=ARGV[1]
    do {
        print num
        num--
    }while(num>0)


}
' $*
Note: The difference from while Yes, do..while is executed once, and then the condition is judged.


4), for
array
awk '
BEGIN{
    arr[1]=1;arr["test"]="test";arr[6]=6
    for(a in arr){
        print a"="arr[a]
    }
}
' $* 


for( expression1; expression2 ; expression3) statement
awk '
BEGIN{
    sum=0
    for(i=1;i<=100;i++){
       sum+=i
    }
    print sum
}
' $*


5), break
for, while, do..while jump out of loop


6 ), continue
for, while, do..while if continue appears, the following commands will not be executed, and directly enter the next loop


7), next 
When the next command is executed, awk will ignore all subsequent awk commands (including All subsequent conditions {instructions}), directly read the next line of data and continue to execute from the first condition {instructions}.
For example : $1~/^a/{...next} {...}
when a switch is used line, skip executing all instructions. The instruction before next will still be executed.


8), exit is to exit the awk program


9), print, printf
printf format output, you can also output to the file
print output string, or variable. Such as: print "id", the id string and the variable are separated by commas, and the OFS variable is used to separate them when printing out. This variable is a space by default


10), close
closes the opened file or pipe


11), system
executes the instructions on the shell.
Such as: awk 'BEGIN{file="test.log" system("rm" file)}'
delete test.log file


12), | can pass data between shell and awk. Refer to getline 


13), delete deletes a value in the array
for( any in X_arr ){
    if(any=="test"){
   delete X_arr[any] #delete only one value at a time
}
}


14), +, -, *, /, %, ^ index, consistent with C language usage.
=, +=, -=, *=, /=, %=, ^= , ++, --
x+=5 means x=x+5


15), ternary operation
condition ?value1:value2


16), Logical operations && || ! 


17), relational operators

>,>=,<,<=,!=,!


Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326742215&siteId=291194637
awk