awk user input

Using the following I'm trying to print the user's response to the prompt Y / N but I get nothing other than the contents of $1?

awk '{
printf($1 " ? (Y/N)")
getline myresponse < "-"
system("read myresponse")
if (myresponse == "Y")
{ print $1 myfrans }
}' $myfile

nawk '
  BEGIN {
     printf "Enter your name: "
     getline name < "-"
     print name
}' < /dev/null
1 Like

Thanks for the reply but this does not work, I need awk (or nawk) to read a file that contains lines, the user is then shown the line and should enter Y to select it or N to skip. If they select Y it should be written into another file or variable for use later in the script.

nawk -f gefa.awk myInputFile

gefa.awk:

function promptMe(myLine,   yn)
{
   printf("Select [%s] (Y/N): ", myLine)
   getline yn < "-"

   return tolower(yn)
}
{
  if (promptMe($0) == "y")
     print "do the YES thingy"
  else
     print "do the NO thingy"
}

Thanks, that is better, but still having problems as it displays all lines from myInputFile without prompting. With system("read") I get the prompts but input is ignored?

Works fines under Solaris 9 "nawk".

I'm using AIX5.2

Many thanks for your help, it works with gawk on AIX.

Don't have AIX in front of me, but.... try this:

function promptMe(myLine,   yn)
{
   printf("Select [%s] (Y/N): ", myLine)
   cmd="read a; echo $a"
   cmd | getline yn
   close(cmd)

   return tolower(yn)
}
{
  if (promptMe($0) == "y")
     print "do the YES thingy"
  else
     print "do the NO thingy"
}

Yes thanks, this works too with awk / nawk.

How do I return the output from the input file back to shell if the answer to the prompt is y?.

function promptMe(myLine,   yn)
{
   printf("Select [%s] (Y/N): ", myLine)
   cmd="read a; echo $a"
   cmd | getline yn
   close(cmd)

   return tolower(yn)
}
{
  if (promptMe($0) == "y")
     print "do the YES thingy with line [$0]"
  else
     print "do the NO thingy with line [$0]"
}

Unfortunately that doesn't return anything from $0, I also want to use the contents of myLine in the shell script rather than $0.

sorry - wrong format of the 'print' statement.
the content of the '$0' is the same as the 'myLine'

function promptMe(myLine,   yn)
{
   printf("Select [%s] (Y/N): ", myLine)
   cmd="read a; echo $a"
   cmd | getline yn
   close(cmd)

   return tolower(yn)
}
{
  if (promptMe($0) == "y")
     print "do the YES thingy with line [" $0 "]"
  else
     print "do the NO thingy with line [" $0 "]"
}

Thanks that displays the contents of myLine within awk, how do I pass the contents back to a shell variable outside of the awk script?.

the general paradigm is:

#!/bin/ksh

myShellVar=$(nawk -f gefa.awk myInputFile)

Thanks but if I do this it does not allow my to input via the gefa.awk.

Many thanks again for all your help, it now works (by redrecting the print statement within gefa.awk.