awk question : system output to awk variable.

Hi Experts,
I am trying to get system output to capture inside awk , but not working:
Please advise if this is possible :

I am trying something like this but not working, the output is coming wrong:

echo "" | awk '{d=system ("date")  ; print "Current date is:" , d }'

Thanks,

In awk, system returns the exit status of the command and not its standard output (unlike command substitution a.k.a. backticks). So, in your case, date will write to standard output wherever that is going.

You could use a pipe instead:

awk 'BEGIN{"date"|getline d; print "Current date is:" , d }'
1 Like

Hi elixir_sinari,
This is great , and worked,
I would like to understand what is

BEGIN{"date"

means, is the double quote

" "

treating date as system command in the BEGIN section.

Thank a lot for your time and valuable answer.
Reveri.

An excerpt from awk manual

expression | getline [var]

Read a record of input from a stream piped from the output of a command. The stream will be created if no stream is currently open with the value 
of expression as its command name. The stream created will be equivalent to one created by a call to the popen() function with the value of expression 
as the command argument and a value of r as the mode argument. As long as the stream remains open, subsequent calls in which expression evaluates 
to the same string value will read subsequent records from the file. The stream will remain open until the close function is called with an expression 
that evaluates to the same string value. At that time, the stream will be closed as if by a call to the pclose() function. If var is missing, $0 and 
NF will be set; otherwise, var will be set. The getline operator can form ambiguous constructs when there are 
unparenthesised operators (including concatenate) to the left of the "|" (to the beginning of the expression containing getline). 
In the context of the "$" operator, "|" behaves as if it had a lower precedence than "$". The result of evaluating other operators is 
unspecified, and portable applications must parenthesis properly all such usages.

system() runs a shell,
so it is more natural to do that in the outer shell

echo "" | awk '{print "Current date is:" , d }' d="`date`"

Of course in this simple case you don't need awk.

$ echo "" | awk '{print "Current date is:" , d }' d=`date`
awk: fatal: cannot open file `Apr' for reading (No such file or directory)
$ echo "" | awk '{print "Current date is: " d }' d="`date`"
Current date is: Mon Apr 22 22:28:42 PDT 2013
1 Like