ldog
ldog

Reputation: 12151

How to use getline in AWK with a command that is concatenated together

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.

Upvotes: 4

Views: 17856

Answers (3)

ghostdog74
ghostdog74

Reputation: 342413

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

Upvotes: 0

ldog
ldog

Reputation: 12151

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.

Upvotes: 9

Mr. Shiny and New 安宇
Mr. Shiny and New 安宇

Reputation: 13908

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 ; 
 }

Upvotes: 2

Related Questions