Function to create the array by reading the file

Tag: unix Author: ximenkai Date: 2009-10-29

I am creating scripts which will store the contents of pipe delimited file. Each column is stored in a separate array. I then read the information from the arrays and process it. There are 20 pipe delimited files and I need to write 20 scripts. The processing that will happen in each script after the information is stored in the array is different. The number of columns in each pipe delimited file is different (but in no case it would be more than 9 columns). I need to do this activity of storing the information in the array in the beginning of each script. The way I am doing it at present is given below. I want help from you to understand how can I write a function to do this activity.

cat > example_file.txt <<End-of-message
some text first row|other text first row|some other text first row
some text nth row|other text nth row|some other text nth row
End-of-message
# Note that example_file.txt will available. I have created it inside the script just to let you know the format of the file
OIFS=$IFS
IFS='|'
i=0
while read -r first second third ignore
do
    first_arr[$i]=$first
    second_arr[$i]=$second
    third_arr[$i]=$third
    (( i=i+1 ))
done < example_file.txt
IFS=$OIFS

Other Answer1

Here is a sort-of minimal change to your script that should get you further...

...
...
while read -r first second third ignore
do
    arr0[$i]=$first
    arr1[$i]=$second
    arr2[$i]=$third
    (( i=i+1 ))
done < example_file.txt
IFS=$OIFS

proc0 () {
  for j in "[email protected]"; do
    echo proc0 : "$j" 
  done
}

proc1 () {
  echo proc1
}

proc2 () {
  echo proc2
}

for i in 0 1 2; do
  t=arr$i'[@]'
  proc$i "${!t}"
done

comments:

Thank you very much. I can take it forward from here.