0

I have an awk script, testscript.script, with command:

$5 > 0 {print $1}

which outputs

 Lebron
 Kobe
 James
 Tony

How can I store this command into a variable var such that when I say print var at any point in the code, the above output will print?

Anonymous
  • 411
  • 1
  • 4
  • 14

1 Answers1

1

You need command substitution, $():

var=$(awk ...)

The STDOUT of the awk command will be saved in variable var.

Now, you can do:

echo "$var"

to get the output.

heemayl
  • 39,294
  • 7
  • 70
  • 76
  • extending this command substitution method to the command `var = $($3 + $4 + $5 > 500 {print $1 $2 | "sort"})` produces syntax errors. What went wrong here? Normally, stdout for this command will display. – Anonymous Nov 02 '16 at 05:30
  • @KevinMoy There must be no spaces around `=`, you need: `var=$(your_command_here)` – heemayl Nov 02 '16 at 05:31
  • very strange... I seem to get syntax errors no matter how simple the command (I even tried `var=$(print "hello world")` and still a failure), and where it was placed in the awk script. Could this be due to having an awk script itself? I invoke the script with `awk -f testscript.script inputfile` – Anonymous Nov 02 '16 at 05:47
  • @KevinMoy Not `print`, use `echo`: `var=$(echo "hello world")` – heemayl Nov 02 '16 at 05:48
  • What if a print statement is combined with an if statement? How would the command substitution change? i.e. storing `if(x > 5) {print "Hello World"}` into the `var` variable? – Anonymous Nov 02 '16 at 06:04