tags:

views:

442

answers:

3

This is driving me insane. All I want to do is pass a command to the terminal from awk, where the command is a string concatenated together made from other variables.

The documentation for awk says that something like

"echo" $1 | getline var

should put the value of $1 into var. But this is not the case. What am I missing here?

I should add that I actually have a loop

for ( i = 1; i <=NF ; i=i+1 )
{
    "echo" $i | getline var
     printf var " "
}

printf "\n"

for inputfile like

 0 2
 1 2

outputs

 0 0
 0 0

what the hell.

+1  A: 

I found two problems with your sample. Your "echo" should be "echo " (at least, for me "echo" didn't work), and your printf is missing the format arg.

for ( i = 1; i <=NF ; i=i+1 ) { 
   "echo " $i | getline var; 
   printf "%s ", var ; 
 }
Mr. Shiny and New
Beat me to it... :-)
Chris J
The format string is optional.
Dennis Williamson
this doesn't seem to be the problem, this seems like a genuine bug in awk to me, If I use your code I get screwy output as well
ldog
A: 

Well, it turns out its not a bug.

Whats going on is the getline opens a new file, and depending on your system settings you can only have X files open per program. Once you max out open files, getline can't open any new fd's. The solution is you have to call

for ( i = 1; i <=NF ; i=i+1 )
{
     command="echo" $i
     command | getline var
     close(command)
     printf var " "

}

printf "\n"

Certainly this is a subtle point and there should be huge warning signs in the documentation about this! Anyways, I'm just glad I solved it.

ldog
A: 

if you want to concatenate values

var=$(awk 'BEGIN{cmd="command "}
{
  for (i=1;i<=NF;i++){
     cmd = cmd" "$i
  }
}
END {
  # pass to shell
   print cmd  
}' file)

$var
ghostdog74