4

There are multiple print statements in my awk program and i want them to pass it back to shell variables. Is it possible.

For eg:

awk '{ r=10; q=20; rr = sprintf("%04.0f", r); qq = sprintf("%05.0f",q); }'

Can i pass the output of rr and qq into two different shell variables?

3 Answers 3

11

The bash read statement can be used to capture awk output into shell variables:

$ read rr qq <<<$(awk 'BEGIN{ r=10; q=20; rr = sprintf("%04.0f", r); qq = sprintf("%05.0f",q); print rr,qq}')
$ echo $rr $qq
0010 00020
Sign up to request clarification or add additional context in comments.

Comments

7

I find it simplest to populate a shell array with the output of the awk command:

$ arr=( $(awk 'BEGIN{ r=10; q=20; printf "%04.0f %05.0f\n",r,q }') )
$ echo "${arr[0]}"
0010
$ echo "${arr[1]}"
00020

then you can do whatever you like in shell with the array, e.g. populate other variables if you like.

Comments

1

The other answers require a Bash shell.

You could also pass the awk output to a function:

process_vars()
{
  var1="$1"
  var2="$2"
}
process_vars $(awk 'BEGIN { print "foo"; print "bar" }')
echo $var1
echo $var2

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.