nextis similar to continue statement but it acts on the default loop that goes through the input records. It doesn't affect BEGIN or END blocks as they are outside the record looping. When next is executed, rest of the statements will be skipped and next input record will be fetched for processing.
$ awk '/\
You'll see more examples with next in coming chapters.
exit
You saw the use of exit earlier to quit early and avoid unnecessary processing of records. If an argument isn't passed, awk considers the command to have finished normally and exit status will indicate success. You can pass a number to indicate other cases.
$ seq 3542 4623452 | awk 'NR==2452{print; exit}' 5993 $ echo $? 0 $ awk '/^br/{print "Invalid input"; exit 1}' table.txt Invalid input $ echo $? 1 $ # any remaining files to be processed are also skipped $ awk 'FNR==2{print; exit}' table.txt greeting.txt blue cake mug shirt -7
If exit is used in BEGIN or normal blocks, any code in END block will still be executed. For more details and corner cases, see gawk manual: exit.
$ # first print is executed $ # on seeing exit, rest of BEGIN and normal blocks are skipped $ # code in END is then executed $ awk 'BEGIN{print "hi"; exit; print "hello"} /^b/; END{print "bye"}' table.txt hi bye
Summary
This chapter covered some of the control flow structures provided by awk. These features makes awk flexible and easier to use compared to sed for those familiar with programming languages.
Next chapter will discuss some of the built-in functions.
Exercises
a) The input file nums.txt contains single column of numbers. Change positive numbers to negative and vice versa. Can you do it with using only sub function and without explicit use of if-else or ternary operator?
$ cat nums.txt 42 -2 10101 -3.14 -75 $ awk ##### add your solution here -42 2 -10101 3.14 75
b) For the input file table.txt, change the field separator from space to , character. Also, any field not containing digit characters should be surrounded by double quotes.
$ awk ##### add your solution here "brown","bread","mat","hair",42 "blue","cake","mug","shirt",-7 "yellow","banana","window","shoes",3.14
c) For each input line of the file secrets.txt, remove all characters except the last character of each field. Assume space as the input field separator.
$ cat secrets.txt stag area row tick deaf chi rate tall glad Bi tac toe - 42 $ awk ##### add your solution here gawk field ice-2
d)Emulate q and Q commands of sed as shown below.
$ # sed '/are/q' sample.txt will print until (and including) line contains 'are' $ awk ##### add your solution here Hello World Good day How are you $ # sed '/are/Q' sample.txt will print until (but excluding) line contains 'are' $ awk ##### add your solution here Hello World Good day
e) For the input file addr.txt: