How can I assign awk's variable to shell script's variable?

I have the following script, and I want to assign the output ($10 and $5) from awk to N and L:

grdinfo data.grd | awk '{print $10,$5}'| read N L

output from gridinfo data.grd is: data.grd 50 100 41 82 -2796 6944 0.016 0.016 3001 2461. where N and L is suppose to be 3001 and 100. I use bash shell.

How can I achieve this? Thanks.

Welcome to the forum.

Depending on your bash version, there are different options:

  • shopt -s lastpipe; set +m

  • read N L <<< $(grdinfo data.grd | awk '{print $10,$5}')

  • read N L <<EOF
    $(grdinfo data.grd | awk '{print $10,$5}')
    EOF

or simply read X X X X L X X X X N <<< $(grdinfo data.grd)

1 Like
eval $(grdinfo data.grd | awk '{printf("N=%s%sL=%s\n", $10,OFS,$5)}')
echo "N->[${N}] L->[${L}]"
2 Likes

Thanks vgersh99 and RudiC. My bash version is: GNU bash, version 4.3.46(7)-release (x86_64-unknown-cygwin)

@vgersh99: although I really love this creative approach, I'm afraid there's a leading $ sign missing in the "command substitution"?

2 Likes

Thanks. I don't know were '$' is missing. can you please point that out? I also found out that '<<<' represent 'here'.

read N L <<< $(grdinfo data.grd | awk '{print $10,$5}')

what is the implication of "<<<" and how can I test the output from this command line? I tried:

read N L <<< $(grdinfo data.grd | awk '{print $10,$5}')
echo N L

Use code tags for code please.

Try

read N L <<< $(grdinfo data.grd | awk '{print $10,$5}')
echo $N $L
1 Like

updated the post with MIA $ .
Thank RudiC

1 Like

I have tested it, the output is correct.

read N L <<< $(grdinfo data.grd | awk '{print $10,$5}')
echo $N $L
1 Like