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?
Best Answer
Here is an example that sorts all lines but the first:
Example
Consider this file:
Then:
The first input line is the first output line. The remaining lines are sorted.