Read array from a file

Hi

I've a config file like:

file1

#comment

k_array: 1 2 3 4 5
n_array: 7 8 9 0 11

I'd like to write a script that read it and store k_array and n_array in 2 arrays.
I mean the script should be able to use both as array.

I've tried to use awk as (only for one array):

k_array2=$(awk '{ for (x = 1; x <= NF; x++) 

arr[x,NR]=$x; 
}
{ if (arr[1,NR] == "k_array:") {
    for(j=2;j<=NF;j++)
        k_array[j-1]=$j;
            
    }
} END{ for(j=1;j<=length(k_array);j++) print k_array[j]}' config_file)

but in this way the returned k_array seems to be a single element array.
In fact with

echo ${k_array2[0]}

I get ------> 1 2 3 4 5.

Any help?

Thanks

D.

One way to do it with Perl:

$
$ cat file1
#comment
 
k_array: 1 2 3 4 5
n_array: 7 8 9 0 11
$
$ perl -lne 'BEGIN{$x=0} chomp; if(/.*: (.*)/){if ($x==0){@a1 = split/ /,$1;$x=1}
>            else{@a2 = split/ /,$1}} END {print "\@a1 = @a1\n\@a2 = @a2"}' file1
@a1 = 1 2 3 4 5
@a2 = 7 8 9 0 11
$
$

Otherwise -

$
$ cat file1
#comment

k_array: 1 2 3 4 5
n_array: 7 8 9 0 11
$
$
$ ##
$ awk 'BEGIN {x=0} {
>       if (/:/ && x==0) { sub(/^.*: /,"",$0); split($0,a1); x=1}
>       else if (/:/ && x==1) { sub(/^.*: /,"",$0); split($0,a2)}
>      } END {
>          for (i=1; i<=length(a1); i++) {print "a1["i"] = "a1}
>          for (i=1; i<=length(a2); i++) {print "a2["i"] = "a2}
>      }' file1
a1[1] = 1
a1[2] = 2
a1[3] = 3
a1[4] = 4
a1[5] = 5
a2[1] = 7
a2[2] = 8
a2[3] = 9
a2[4] = 0
a2[5] = 11
$
$

tyler_durden

What shell you're using?

In bash or (I think) ksh93:

set -f  ## not necessary with example given.
while IFS= read -r line
do
  case $line in 
    *array:*) name=${line%%:*}
              eval "$name=( ${line#*:} )"
              ;;
  esac
done < "$file"
set +f

hi

i use /bin/bash

@durden_tyler: thx for the code.

@cfajohnson: thx for the code too

I'm checking out that someone to put the result in one array use:

set -A k_array2 `awk '{ code awk that return array} '`

is it correct? becouse i get an error as invalid option for set

thanks

D

Using Bash, I get almost the same as cfajohnson

while read line 
 do
   [[ $line =~ ^._array ]] && eval "${line%:*}=( ${line#*:} )"
done < configFile1