I want to run a shell command in awk. Shell commands often take stdin and write to stdout.

print to_sort | "sort"
"sort" | getline

is not working (sort on second line waits for input)

print to_sort | "sort" | getline

is a syntax error.


GNU awk knows coprocesses that can do that. It's manual also describes why what you're doing doesn't work: the two commands used in the pipe are distinct subprocesses, even though they're started with the same command line. To get input and output to and from the same subprocess, use |& on both pipes:

awk 'BEGIN {com = "cat -n"} {print |& com; com |& getline; print}'

That doesn't really help you with sort, though, since sort doesn't produce any output until it sees an EOF on it's input.

With commands like that, you need to give all the output first, close the write end of the coprocess pipe, and only then start reading from it. E.g.

awk 'BEGIN {com="sort"} {print |& com} END { print "---"; close(com, "to"); while(com |& getline) print }'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.