Save multiple results from AWK to shell variables

435 views Asked by At

Save multiple results from an AWK script to c shell variables.

I have a simple AWK script running in the terminal to find max and min from an input text file.

How do we save this max and min values to c shell variable in order to use it later.

Here is the AWK

awk 'NR == 1 { xmax=$1; xmin=$1 } \
    { if ($1>xmax) xmax=$1; if ($1<xmin) xmin=$1;} \
    END {printf "X-Min: %d\tX-Max: %d\n", xmin, xmax}' $inpfile

I want to save this in already defined variables lets say $xmin and $xmax

Any suggestion would be a great help, I have no prior experience with SHELL and AWK.

1

There are 1 answers

0
shellter On

As others have said, you can't pass values from awk to the shell.

You'll need to rely on the shells ability to perform cmd-substitution.

Back when all I had was csh, I would have done

setenv xmin_xmax = `awk 'NR == 1 { xmax=$1; xmin=$1 } \
{ if ($1>xmax) xmax=$1; if ($1<xmin) xmin=$1; printf("%d|%d\n", xmin, xmax}' $inpfile`

setenv xmin = `echo "$xmin_xmax" | sed 's/|.*$//'`
setenv xmax = `echo "$xmin_xmax" | sed 's/*.|//'`

Sorry but I don't have access to a csh to test this with now. As you're inside a cmd-substitution with your awk, you'll probably need more continuation chars \ to connect those lines.

If you have trouble with this, post the error messages as comments, and I'll see if I can remember the special csh incantations.

EDIT Or see Grymoire CSH tips for how to use array variables in csh. (I don't recall this!)

IHTH