Results 1 to 3 of 3
  1. #1
    Join Date
    Jan 2007
    Posts
    2

    Unanswered: How to create Array variable?

    Hi,
    I am new for ksh program. My program reads a comma delimited text file, assign each field's value into a array variable.
    Listed below was my code, but the result wasn't the way i want.

    custid=`awk 'BEGIN {FS=",";j=0}
    {custid[j] = $1
    j++}
    END {for(i=0;i<=j;i++)
    print custid[i]}' $custid_file_name`

    The variable $sustid shows "1101 1102", but what I want is:
    $sustid[0]=1101
    $sustid[1]=1102

    Please help! Thanks.

    Gary

  2. #2
    Join Date
    Aug 2006
    Location
    The Netherlands
    Posts
    248
    Hi,

    The way you're trying to assign values to the custid variable will not work because the AWK output will be regarded as one string, as you noticed. I think you should choose the environment in which to do both the assingment and further processing of the array. And if it's impossible to do the complete handling of the array in AWK you'd better try to fill the array in shell script.
    Since your AWK program only reads the first field of every record you could do the same with 'sed' for instance, like:
    Code:
    #!/usr/bin/ksh                                      
                                                        
    i=0                                                 
    for field in `cat custid_file_name | sed 's/,.*$//'`
    do                                                  
       var[$i]=`echo $field`                            
       ((i=$i+1))                                        
    done                                                
                                                        
    j=0                                                 
    while [ $j -lt $i ]                                 
    do                                                  
       print ${var[$j]}                                 
       ((j=$j+1))                                        
    done
    With this you've loaded the array completely in the shell environment. And for loading the same array in AWK (which is not available in the shell environment) I would do it like:
    Code:
    #!/usr/bin/ksh                         
                                           
    awk -F "," '{  var[NR] = $1   }     
          END   {  for(i = 1; i <= NR; i++)
                      print var[i]      
                }' custid_file_name
    where NR is the builtin variable for recordnumber read and the -F flag sets the fieldseparator.

    Regards
    Last edited by Tyveleyn; 01-26-07 at 19:47.

  3. #3
    Join Date
    Jan 2007
    Posts
    2
    Tyveleyn,

    Thank you very much for reply my question and the explanation.

    Happy Friday.

    Gary

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •