0

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.

Indigo
  • 2,887
  • 11
  • 52
  • 83
  • You say "c shell", but tagged the question as `bash`. Which shell do you mean? – chepner Mar 12 '14 at 14:21
  • sorry its c shell, just removed the bash tag – Indigo Mar 12 '14 at 14:23
  • print them from awk, parse it from csh. – Karoly Horvath Mar 12 '14 at 14:29
  • @KarolyHorvath : As I said, I have no experience with csh, so the question, what do you mean by parse it from csh. Please check the updated code in question. Thanks – Indigo Mar 12 '14 at 15:01
  • @Indigo: sorry, I'm not familiary with csh. but the idea is: parse a text like `2 5` o `2,5` into the two variables. one hit I've found: http://stackoverflow.com/questions/7735160/how-do-i-split-a-string-in-csh I'm sure there are many links for this, as it is a common task – Karoly Horvath Mar 12 '14 at 15:23

1 Answers1

1

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

shellter
  • 36,525
  • 7
  • 83
  • 90