Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

getline

awk

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.

like image 256
ldog Avatar asked Oct 24 '25 18:10

ldog


1 Answers

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.

like image 96
ldog Avatar answered Oct 26 '25 20:10

ldog