tags:

views:

701

answers:

2

Hi,

I want to run the system command in a awk script and get its output stored in a variable. I've been trying to do this, but the command's output always goes to shell and I'm not able to capture it. Any ideas on how this can be done?

Example:

$ date | awk --field-separator=! {$1 = system("strip $1"); /*more processing*/}

Should call the strip system command and instead of sending the output to the shell, should assign the output back to $1 for more processing. Rignt now, its sending output to shell and assigning the command's retcode to $1.

Thanks for any help

A: 

Figured out.

We use awk's Two-way I/O

{
  "strip $1" |& getline $1
}

passes $1 to strip and the getline takes output from strip back to $1

Sahasranaman MS
+1  A: 

Note: Coprocess is GNU awk specific. Anyway another alternative is using getline

cmd = "strip "$1
while ( ( cmd | getline result ) > 0 ) {
  print  result
} 
close(cmd)
ghostdog74
Sahasranaman MS
yes, shouldn't be an issue. still you should check documentation and see if coprocess is only available in certain version of gawk. i can't remember on top of my head
ghostdog74
From version 3.1. RedHat has 3.1.5. Anyways I'll use the way you suggested, unless I want to send something to stdin of the command, in which case coprocess is helpful.
Sahasranaman MS