Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How to pass variable in awk

Status
Not open for further replies.

ssandip

Technical User
Apr 9, 2001
2
US
Hi,

Is there any way to pass variable in awk statement. I am trying to write following script which will keep variable in array.
------------------------------------------------
sys="abc bcd dde ccc"
ctr=1
SYSNAME=${sysname[*]}
sysn=`echo $sys | awk '{print NF}'`
while [ $sysn -ge $ctr ]
do
sysname[$ctr]=`echo $sys | awk -F" " '{print $ctr}'`
((ctr=ctr+1))
done
--------------------------------------------------
It is showing following error

awk: Field $() is not correct.
The input line number is 1.
The source line number is 1.

Is there any other way to store those variable.

Thanks in advance.

Sandip
 
sysname[$ctr]=`echo $sys | awk -F" " '{print $ctr}'`

The [tt]-F" "[/tt] isn't needed.

[tt]
sysname[$ctr]=`echo $sys | awk -v ctr=$ctr '{print $ctr}'`
[/tt]
 
Looks to me like you're using awk to copy the array $sys into the array $sysname. This is an awfully roundabout way of doing things. However, you can do it this way if you insist. Use the -v option to pass the $ctr variable into awk. See bolded:
Code:
sys="abc bcd dde ccc"
ctr=1                                                  
SYSNAME=${sysname[*]} [b]# don't know what this line does?[/b] 
sysn=`echo $sys | awk '{print NF}'`                    
while [ $sysn -ge $ctr ]                               
do                                                     
  sysname[$ctr]=`echo $sys | [b]awk -v ctr=$ctr[/b] '{print $ctr}'` 
  ((ctr=ctr+1))                                        
done
However, wouldn't it be easier just to say sysname=$sys instead of going through all this? (My shell scripting is very rusty, but I tried this and it worked.)




 
Thanks a lot to both of you.. Yes it worked... Can I use awk array function to store those variable..
 
You don't say which shell you are using, but you can define an array with values in bash or ksh.

bash:
[tt] declare -a sysname=($sys)[/tt]

ksh:
[tt] set -A sysname $sys[/tt]
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top