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?

0

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

5 Comments

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.
@KevinMoy There must be no spaces around =, you need: var=$(your_command_here)
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
@KevinMoy Not print, use echo: var=$(echo "hello world")
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?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.