This is a use case I am continually running into in parsing CSV files.  When it is an inline awk script embedded in a shell script, I can use this workaround:
myfile="$(mktemp)"
awk '(awk script here)' > "$myfile"
head -1 "$myfile"
sed 1d "$myfile" | sort
rm "$myfile"
(Or using appropriate mktemp template for BSD mktemp; GNU works as above.)
However, when writing a full fledged awk script with a shebang #!/bin/awk -f, I don't want to have to change it to a shell script just to handle this one factor of sorting the output.
How can I do this in awk? Or, if there is no native sort function in awk, where can I learn about awk pipelines and how can I use pipelines to accomplish this without changing the shebang?
echothe headers to the final filename right off the bat. Then I do all of my sorting in the temporary file, and when I'm done,cat tmpfile >> final.csv; rm tmpfile.awkscript. In cases where the header is going to be parsed and changed inawkand change the behavior of theawkscript (for example, allowing your input columns in arbitrary sequence as long as the headers match pre-defined values in some sequence, and then always outputting a specific column sequence), you need to handle both the header and the content within the same awk script. Thus my question. (That is just one example use case; there are others.)stderrcould be an option.asortto sort by value, andasortito sort by index.