1748202 Members
2908 Online
108759 Solutions
New Discussion юеВ

Re: about getline in awk

 
SOLVED
Go to solution
Jdamian
Respected Contributor

about getline in awk

Hi

I'm trying to insert the string hour:minute:second at the begin of each line of a command output:

function ins
{
awk '{ "date +%H:%M:%S" | getline D; print D" "$0 }'

return 0
}

integer I=0
while (( I<5 ))
do
print $I
sleep 1

I=I+1
done | ins

but the output is:

10:25:30 0
10:25:30 1
10:25:30 2
10:25:30 3
10:25:30 4

It looks like the awk line "date +%H:%M%S | getline D" only is executed one time.
I'm a mess.

what is wrong ?
13 REPLIES 13
Massimo Bianchi
Honored Contributor

Re: about getline in awk

Hi,
i think the line is correct, it is you that execute it only once !

Try this

integer I=0
while (( I<5 ))
do
D=$(ins)
print $I
sleep 1

I=I+1
done

So it should be execute each time you run the script, and not only once.


HTH,
Massimo

Massimo Bianchi
Honored Contributor

Re: about getline in awk

Hi,
i think the line is correct, it is you that execute it only once !

Try this

integer I=0
while (( I<5 ))
do
D=$(ins)
print $D $I
sleep 1

I=I+1
done

So it should be execute each time you run the script, and not only once.


HTH,
Massimo

Jdamian
Respected Contributor

Re: about getline in awk

I don't understand your answers.

According to awk man pages, the awk action

{ "date +%H:%M:%S" | getline D; print D" "$0 }

is executed on every input line not on every awk execution, isn't it ?
Jdamian
Respected Contributor

Re: about getline in awk

on other words... If a input file is 20 lines long, how many times is executed the command:

date +%H:%M:%S
?
Massimo Bianchi
Honored Contributor

Re: about getline in awk

Hi,
yes, you are right.

Sorry I made a mistake, It seemed to me your line was

" done < ins "


Massimo

Dietmar Konermann
Honored Contributor
Solution

Re: about getline in awk

Try this:

function ins
{
awk '{ "date +%H:%M:%S" | getline D; print D" "$0; close("date +%H:%M:%S") }'

return 0
}
"Logic is the beginning of wisdom; not the end." -- Spock (Star Trek VI: The Undiscovered Country)
Robin Wakefield
Honored Contributor

Re: about getline in awk

Hi,

You need to close the pipe, since awk cannot open more than one at a time:

function ins
{
awk '{ "date +%H:%M:%S" | getline D;close "date +%H:%M:%S"; print D" "$0 }'

return 0
}

integer I=0
while (( I<5 ))
do
print $I
sleep 1

I=I+1
done | ins


rgds, Robin
Massimo Bianchi
Honored Contributor

Re: about getline in awk

HI,
I thank all the others for the answers, today i learnt something new about awk !

Massimo
Jdamian
Respected Contributor

Re: about getline in awk

Dietmar, your suggestion produces no change in the output.

I also ran the same script on a Solaris 8 system (/usr/xpg4/bin/awk is used instead of SunOs awk). The output is:

10:21:54 0
1
2
3
4
5
6
7
8
9

I suspect 'date' is executed just one time.