Awk – get input from both file and STDIN

awkinput

Is it possible to get input from both file and the terminal?
I wish to ask the user something in the END portion of the awk script.

That input should be typed in by the user and not read from the file which had the data to be processed.

END {
  getline choice
  if(choice == "Y")
    print "OK"
}

But choice is read off the input file.

Best Answer

You can read from /dev/tty or from /dev/stdin.

getline choice < "/dev/tty"

/dev/tty is pretty ubiquitous (even one the very few, along with /dev/null and /dev/console to be required by POSIX), /dev/stdin is less common, but at least GNU awk would recognize it as meaning stdin even if the system doesn't have such a device/special file.

On Linux (and Cygwin, but not other Unix-likes), reading from /dev/stdin is not the same as reading from stdin (fd 0), but instead means reading from the same file as open on fd 0. If that file is a regular file for instance, that would start reading from the start of the file instead of where fd 0 currently points to in the file.

Because GNU awk handles paths like /dev/stdin by itself (and treat it as reading from stdin), on Linux or Cygwin it would behave differently from other applications that don't do that special handling. If you wanted the Linux/Cygwin behaviour in gawk (which here is likely not your case), you could either use ///dev/stdin or /dev/./stdin for gawk to stop recognising it as the /dev/stdin special case, or probably better here if you intend to rely on Linux/Cygwin specific behaviour, use the Linux/Cygwin specific /proc/self/fd/0 path (which /dev/stdin actually symlinks to on those systems).

Related Question