Awk tutorial: awk loop example: awk for and while

If you want to program with the linux awk command, you have to learn the loop.

The awk loop mainly includes for and while.

awk for loop

First, let’s execute the following command to see what we can get.

➜ awk -F"#" '{
        for(i=1;i<=NF;i++) {
                if($i == "google") {
                        print "NF=" i ", this is a refer";
                } else {
                        print "NF=" i "," $i
}' test-2.txt

The content of test-2.txt is:

The result of the above command is this:

NF=4, this is a refer
linux awk for loop

So how is the above awk command executed? Let’s look at it line by line.

1. awk -F”#”

Cut the contents of the file test.txt according to "#", that is:

field 1:
field 2:
field 3: /url/test
field 4: google
field 5: 1234322344

2. for(i=1;i<NF;i++)

NF: number of fields in the current record.
$0: complete input record.

Because $0 in the linux awk command represents a complete input record, the number of fields counts from 1.

The for loop above means looping from 1 to NF-1.

3. if($i == “google”) {print “NF=” i “, this is a refer”;}

$i: which represents the value of the i-th field.

Here is to check which field's value is "google", and if the field value is google, output the string.

4. else { print $i}

if the field value is not google, output its value.

Ok, the above command has already been introduced.

However, in some cases we also need to use awk for to process some arrays. How do we do this?

awk for loop array

➜ awk 'BEGIN{
        a["k-my"] = "my";
        a["k-name"] = "name";
        a["k-is"] = "is";
        a["k-ylspirit"] = "ylsprit";

        for(i in a) {
                print i, ": " a[i]
for(i in a) 

i: represents the key of array a.
a[i]: represents the value of array a.

awk while loop

➜  awk -F"#" '{
	i = 0;

	while(i<=NF) { 
		print i ": "$i; 
}' test-2.txt
Linux awk while loop, i starts at 0, increments by 1 each time, until i equals the number of fields NF exits the loop.


Related post

awk command tutorial in linux/unix with examples and use cases
Awk tutorial: awk merge files base on the keyword
AWK tutorial: awk custom function and awk example
Awk tutorial: find and kill process use awk
Awk tutorial: awk -F and awk BEGIN{ FS … }
Awk tutorial: awk regex example
Awk tutorial: awk loop example: awk for and while
awk if else, if else if else and awk if else nested example
Awk tutorial: awk NR FNR difference
Awk tutorial: awk sort uniq
Awk tutorial: split on character awk or cut
Awk tutorial: awk newline character
Awk tutorial: three ways of awk execution
How to print tree directory structure in linux/unix
Linux shell batch move files, delete spaces, rename files
Awk tutorial: awk group by count

One Comment

Add a Comment

Your email address will not be published. Required fields are marked *