GIs there a way to make awk interactive when it is processing /dev/stdin via a pipe.
Imagine I have a program which continuously generates data. Example :
$ od -vAn -tu2 -w2 < /dev/urandom
2357
60431
19223
...
This data is being processed by a very advanced awk script by means of a pipe :
$ od -vAn -tu2 -w2 < /dev/urandom | awk '{print}'
Question: Is it possible to make this awk program interactive such that :
- The program continuously prints output
- When a single key is pressed (eg.
z), it starts to output only0for each line it reads from the pipe. - When the key is pressed again, it continues to output the original data, obviously skipping the already processed records it printed as
0.
Problems:
/dev/stdin(also referenced as-) is already in use, so the keyboard interaction needs to be picked up with/dev/ttyor is there another way?getline key < "/dev/tty"awaits untilRSis encountered, so in the default case you need to press two keys (z and Enter) :$ awk 'BEGIN{ getline key < "/dev/tty"; print key}'This is acceptable, but I would prefer a single key-press.
So, is it possible to set
RSlocally such thatgetlinereads a single character? This way we could locally modifyRSand reset it after thegetline. Another way might be using the shell functionread. But it is incompatible betweenbashandzsh.getlineawaits for input until the end-of-time. So it essentially stops the processing of the pipe. There is agawkextention which allows you to set a timeout, but this is only available sincegawk 4.2.So I believe this could potentially work :awk '{print p ? 0 : $0 } { PROCINFO["/dev/tty", "READ_TIMEOUT"]=1; while (getline key < "/dev/tty") p=key=="z"?!p:p }However, I do not have access to
gawk 4.2(update: this does not work)
Requests:
- I would prefer a full POSIX compliant version, which is or entirely awk or using POSIX compliant system calls
If this is not possible, gawk extensions prior to 3.1.7 can be used and shell independent system calls.- As a last resort, I would accept any shell-awk construct which would make this possible under the single condition that the data is only read continuously by
awk(so I'm thinking multiple pipes here).