[Copyright statement: reprinted. Please retain the Source: blog.csdn.net/gentleliu. Mail: shallnew at 163 dot com]
Like printf in the previous section, the cycle judgment of awk is similar to the cycle judgment Syntax of C language.
1. While Loop
#!/bin/sh awk 'BEGIN { ORS=""}{ i=0 while (i < NF) { printf("* ") i++ } print "\n"}' group_file1
First, set the ORs delimiter of the output record to "" (null), which causes the print statement to not output a new line at the end of each call. This means that if you want any text to start from a new line, You need to explicitly write print "\ n ".
In the Code, set variable I to store the number of fields currently being processed. For each record, set I to 0 first, and then print a "*" for each field. after each line of record is printed, a line feed is printed. Because ORs is set to "", no two line breaks are output in print. The output is as follows:
#./7_awk_while.sh* * * * * * * * * * * * * * * * #
2. Do... While Loop
Awk also has a "do... while" loop, which evaluates the condition at the end of the code block, not at the beginning as the standard while loop.
Example (six * numbers are output ):
#!/bin/sh echo "" | awk '{ i=0 do { printf("* ") }while (i++ < 5) printf("\n")}'
Unlike the General while loop, because the condition is evaluated after the code block, the "Do... while" loop will always be executed at least once.
In other words, when a regular while loop is first encountered, if the condition is false, the loop will never be executed.
3. For Loop
Awk allows the creation of a for loop, which is like a while loop, which is also equivalent to a For Loop in C language:
for ( initial assignment; comparison; increment ) { code block}
Example (five consecutive outputs *):
#!/bin/sh echo"" | awk '{ for (i=0; i<5; i++) { printf("* ") } printf("\n")}'
After using the C language, we will find that the cycle operation of awk is very similar to the cycle operation syntax of the C language.
Awk also supports arrays. You do not need to define or specify the number of array elements before using arrays. Loop is often used to access arrays. The following is the basic structure of a loop type:
For (element inarray) print array [element]
Example:
#!/bin/sh echo"" | awk 'BEGIN { a[1]="123" a[2]="456" a[3]="789"} END{ for(i in a) { print a[i] }}'
The subscript of the awk array can also be a string. Awk regards arr ["1"] and ARR [1] As the same element.
Example:
#!/bin/sh echo"" | awk 'BEGIN { a[1]="123" a[2]="456" a[3]="789" a["hello"]="awk" a["3"]="world"} { for(i in a) { print a[i] }} END { print "======end========" print a[3] print a["3"]}'
Output result:
awk123456world======end========worldworld
Shell text filtering programming (6): loop judgment and array of awk