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

Summary of common commands in Dockerfile

Syntax composition: 1 Annotation information 2 Co...

Summary of methods for inserting videos into HTML pages

Now if you want to use the video tag in a page, y...

Detailed tutorial on VMware installation of Linux CentOS 7.7 system

How to install Linux CentOS 7.7 system in Vmware,...

Completely uninstall mysql. Personal test!

Cleanly uninstall MySQL. Personally tested, this ...

How to use Portainer to build a visual interface for Docker

Portainer Introduction Portainer is a graphical m...

Solution to MySQL remote connection failure

I have encountered the problem that MySQL can con...

How to monitor global variables in WeChat applet

I recently encountered a problem at work. There i...

Implementing a simple timer in JavaScript

This article example shares the specific code of ...

Three ways to implement virtual hosts under Linux7

1. Same IP address, different port numbers Virtua...

Simple example of HTML text formatting (detailed explanation)

1. Text formatting: This example demonstrates how...

Mysql sorting and paging (order by & limit) and existing pitfalls

Sorting query (order by) In e-commerce: We want t...

Tutorial analysis of quick installation of mysql5.7 based on centos7

one. wget https://dev.mysql.com/get/mysql57-commu...

10 ways to view compressed file contents in Linux (summary)

Generally speaking, when we view the contents of ...

How to solve the problem of case insensitivity in MySQL queries

question Recently, when I was completing a practi...