Using a while Construct and Setting Variables
In this section, I’ll show you two new concepts at once. You’ll see how to use a while
loop, and how to use awk
programming variables. Let’s begin with something simple.
Summing Numbers in a Line
In this scenario, we have a file with several lines of numbers. We want to add the numbers on each line and show the sum for each line. First, create the input file and make it look something like this numbers_fields.txt
file:
38 87 389 3 3432
34 13
38976 38 198378 38 3
3878538 38
38
893 18 3 384 352 3892 10921 10 384
348 35 293
93 1 2
1 2 3 4 5
This looks like quite a challenging task because each line has a different number of fields. But, it’s actually quite easy. Here’s the add_fields.awk
script that does the job:
#!/usr/bin/awk -f
{
addend=1
sum=0
while (addend <= NF) {
sum = sum + $addend
addend++
}
print "Line " NR " Sum is " sum
}
The first...