Using loops in awk

Using loops in awk

Let's learn about different types of loops that execute the same command multiple times.

An awk script has three main parts: BEGIN and END functions (both optional), and the function written by the user to be executed each time. In a way, the main body of awk is a loop because the commands in the function are executed once for each record. However, sometimes you want to execute multiple commands on a record, then you need to use a loop.

There are many types of loops, each suitable for different scenarios.

While Loop

A while loop tests an expression and executes commands if the expression is true. When the expression becomes false, the loop breaks.

#!/bin/awk -f
BEGIN {
    # Loop through 1 to 10
  i=1;
  while (i <= 10) {
    print i, "to the second power is ", i*i;
    i = i+1;
  }
exit;
}

In this simple example, awk prints the square of the integer value placed in the variable i. The while (i <= 10) statement tells awk to execute the loop only while the value of i is less than or equal to 10. After the loop is executed for the last time (the value of i is 10), the loop terminates.

do-while loop

The do-while loop executes the commands following the keyword do. A test expression is checked at the end of each iteration to determine whether to terminate the loop. The command is executed repeatedly only while the test expression returns true (that is, the condition that terminates the loop has not yet been reached). If the test expression returns false, the loop is terminated because the condition to terminate the loop is reached.

#!/usr/bin/awk -f
BEGIN {
    i=2;
    do {
        print i, "to the second power is ", i*i;
        i = i + 1
    }
    while (i < 10)
exit;
}

for loop

There are two kinds of for loops in awk.

A for loop initializes a variable, checks a test expression, increments the variable, and continues looping as long as the expression evaluates to true.

#!/bin/awk -f
BEGIN {
  for (i=1; i <= 10; i++) {
    print i, "to the second power is ", i*i;
  }
exit;
}

Another for loop sets an array variable with consecutive indices and executes a set of commands for each index. In other words, it uses an array to "collect" the results of each command execution.

This example implements a simplified version of the Unix command uniq. By adding a series of strings as keys to array a and incrementing the key value when the same key appears again, you can find out how many times a string appears (just like the --count option of uniq). If you print all the keys of the array, you will get all the occurrences of the string.

Take the demo file colours.txt (the file in the previous article) as an example:

name color amount
apple red 4
banana yellow 6
raspberry red 99
strawberry red 3
grape purple 10
apple green 8
plum purple 2
kiwi brown 4
potato brown 9
pineapple yellow 5

Here's a simple awk version of uniq -c:

#!/usr/bin/awk -f
NR != 1 {
  a[$2]++
}
END {
  for (key in a) {
        print a[key] " " key
  }
}

The third column of the example data file is a count of the entries listed in the first column. You can use an array and a for loop to count the entries in the third column by color.

#!/usr/bin/awk -f
BEGIN {
  FS=" ";
  OFS="\t";
  print("color\tsum");
}
NR != 1 {
  a[$2]+=$3;
}
END {
  for (b in a) {
    print b, a[b]
  }
}

You can see that we also need to print a column header in the BEFORE function (which is executed only once) before processing the file.

cycle

Loops are an important part of any programming language and awk is no exception. Using loops you can control how the awk script runs, what information it counts, and how it processes your data. We will discuss switch, continue, and next statements in our next article.

ps: Simple usage of awk-for loop

text:

[root@VM_0_84_centos ~]# cat sshd.txt
1 2 3
4 5 6
7 8 9

Loop to print the above text

Fixed format of for loop i=1 sets the initial variable of i i<=NF i variable is less than or equal to the value of NF variable (number of fields per row) i++ means i is incremented by +1,

[root@VM_0_84_centos ~]# cat sshd.txt |awk '{for(i=1;i<=NF;i++){print $i}}'
1
2
3
4
5
6
7
8
9

Summarize

The above is my introduction to using loops in awk. I hope it will be helpful to you. If you have any questions, please leave me a message and I will reply to you in time. I would also like to thank everyone for their support of the 123WORDPRESS.COM website!
If you find this article helpful, please feel free to reprint it and please indicate the source. Thank you!

You may also be interested in:
  • Usage of awk command in Shell script
  • Detailed examples of how to use awk regular expressions and built-in functions
  • Shell regular expressions: grep, sed, awk practical notes
  • Summary of the usage of split function in awk in Linux
  • Awk command to count the number of times a keyword appears in a file
  • How to process the last line of a file using sed or awk
  • Awk interval value example
  • Awk introduction and study notes collection

<<:  The whole process record of Vue export Excel function

>>:  The latest graphic tutorial of mysql 8.0.16 winx64 installation under win10

Recommend

Optimized record of using IN data volume in Mysql

The MySQL version number is 5.7.28. Table A has 3...

How to monitor Tomcat using LambdaProbe

Introduction: Lambda Probe (formerly known as Tom...

How to use multi-core CPU to speed up your Linux commands (GNU Parallel)

Have you ever had the need to compute a very larg...

How to build Nginx image server with Docker

Preface In general development, images are upload...

WeChat applet implements calculator function

WeChat Mini Programs are becoming more and more p...

jQuery implements breathing carousel

This article shares the specific code of jQuery t...

Why not use UTF-8 encoding in MySQL?

MySQL UTF-8 encoding MySQL has supported UTF-8 si...

CSS implements a pop-up window effect with a mask layer that can be closed

Pop-up windows are often used in actual developme...

Docker installation tomcat dubbo-admin instance skills

1. Download the tomcat image docker pull tomcat:8...

How to use async await elegantly in JS

Table of contents jQuery's $.ajax The beginni...

How to query whether the mysql table is locked

Specific method: (Recommended tutorial: MySQL dat...

Understanding JavaScript prototype chain

Table of contents 1. Understanding the Equality R...

CentOS 7 cannot access the Internet after modifying the network card

Ping www.baidu.com unknown domain name Modify the...

How to set mysql permissions using phpmyadmin

Table of contents Step 1: Log in as root user. St...