4

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.

| improve this question | | | | |
  • 1
    awk was not really designed for interactive use. You can pass choice directly to awk like awk -f script.awk -v choice=Y, and use a wrapper shell script to do the interactive part. If you really need to wait until the END block to ask for choice, you could try getline < "/dev/tty" as a not terribly portable workaround. – jw013 Nov 12 '12 at 15:58
6

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).

| improve this answer | | | | |
2

As can be seen, - also works:

getline < "-"

Or

getline variable < "-"
| improve this answer | | | | |

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.