Search code examples
awkscriptingpiping

Awk script piping changes apparent execution order


Following is a segment of my script:

END{
    for (key in data) {
        print key" "data[key]|"sort -k 2n";
    }
    print "something or other"
}

The problem is, that the console output first shows the second print output, and then shows the result of the print outputs piped through sort in the for loop.

Tried cruly braces to no avail. I have no idea how to even google about this problem, how does sort collect what it should sort? How can I direct it better?

Edit: Just had a moment of realization, the problem is not that it catches the last print, but that it actually gets executed after the last print, despite being called earlier.


Solution

  • The answer is the close() function suggested by Ed Morton.

    For details about close(), I found https://www.gnu.org/software/gawk/manual/html_node/Close-Files-And-Pipes.html to be useful.

    The correct code segment thus became:

    END{
        for (key in data) {
            print key" "data[key]|"sort -k 2n";
        }
        close("sort -k 2n");
        print "something or other";
    }
    

    this way, it correctly prints out the sorted output from the for loop, and only after that prints out the last print output called after the loop.