Re: Setting Multiple Shell Variables from One Run of awk



On 09/30/2008 01:48 PM, Martin McCormick wrote:
Right now, I have a shell script that does the following:

hostname=`echo $NEWDEV |awk 'BEGIN{FS="."}{print $1}'`
domain=`echo $NEWDEV |awk 'BEGIN{FS="."}{print $2}'`
top0=`echo $NEWDEV |awk 'BEGIN{FS="."}{print $3}'`
top1=`echo $NEWDEV |awk 'BEGIN{FS="."}{print $4}'`

That looks inefficient (dumb) so I ask, is there a way
to assign the fields in an awk expression to shell variables as
one runs awk once?

Being able to do that would mean one run of awk instead
of the 4 shown here and, if file accesses are involved, there is
only one of those.

Thanks.

Martin McCormick WB5AGZ Stillwater, OK Systems Engineer
OSU Information Technology Department Telecommunications Services Group



The bash shell can do this internally since it supports arrays:

NEWDEV=${NEWDEV//./ }
NEWDEV=($NEWDEV)
echo "hostname: ${NEWDEV[0]}"
echo "domain: ${NEWDEV[1]}"
echo "top0: ${NEWDEV[2]}"
echo "top1: ${NEWDEV[3]}"

Of course you're free to assign the array elements to variables if you desire. See "man bash" for more about arrays.



--
To UNSUBSCRIBE, email to debian-user-REQUEST@xxxxxxxxxxxxxxxx with a subject of "unsubscribe". Trouble? Contact listmaster@xxxxxxxxxxxxxxxx



Relevant Pages

  • Re: Setting Multiple Shell Variables from One Run of awk
    ... to assign the fields in an awk expression to shell variables as ... Martin McCormick WB5AGZ Stillwater, OK ... but it takes both awk and shell to do it. ... And, because the awk script has a bunch of stuff in it that the shell recognizes, this works best if you can put the script in a file. ...
    (Debian-User)
  • Re: Importing Shell Variables in to awk from Shell Scripts
    ... Martin McCormick writes: ... > text and, if the sixth field in a line matches a search string, print ... This seems like a good job for awk and, ... vars, but your awk syntax is wrong. ...
    (Debian-User)
  • Re: awk and date command
    ... awk -v DT=`date +%Y%m%d` program.awk record.txt ... Country: Australia ... Text or chat with friends inside Yahoo! ... To unsubscribe: ...
    (Fedora)
  • Re: awk and date command
    ... but i don't know how to put the hostname in awk ... Text or chat with friends inside Yahoo! ... To unsubscribe: ...
    (Fedora)
  • Re: awk and date command
    ... Use a printf statement as follows: ... P.S. Awk! ... Text or chat with friends inside Yahoo! ... To unsubscribe: ...
    (Fedora)