NandaKumar
NandaKumar

Reputation: 905

awk exiting the ACTION path and going directly to END part

I am using an awk script and the skeleton of the same is simple

 awk '
 BEGIN {
     Variable declaration
 }
 {
    ACTION PART
 }
 END
 {
 }' FILE A

The file A is such a huge file. So I wanted not to traverse the entire file and so what I am trying to do is, I am trying to keep some checks in ACTION PART in such a way that if that check is successful, then I need to skip reading the rest part of the file and directly go to END part.

My question is how would I redirect the script from ACTION PART to END Part based on the condition.. I am looking for some kind of command like "break" in for loop. Could you people share your ideas. Thank you.

Upvotes: 7

Views: 5003

Answers (2)

Dennis Williamson
Dennis Williamson

Reputation: 360495

The exit command will do what you want.

From the man page:

Similarly, all the END blocks are merged, and executed when all the input is exhausted (or when an exit statement is executed).

Upvotes: 13

Justas Butkus
Justas Butkus

Reputation: 533

Use "exit" as it terminates current block, but END is still handled. See example bellow.

$ cat test.input
hello
world
one

$ awk 'BEGIN { print "Start-up"} {print "Read:", $1; if ($1 == "world") {exit}} END {print "Phase-out"}' test.input 
Start-up
W: hello
W: world
Phase-out

Upvotes: 4

Related Questions