0

First I should perhaps explain what I want to do...

  • I have 'n' amounts of files with 'n' amount of lines. All I know is that the line count will be even.
  • The user selects the files that they want. This is saved into an array called ${selected_sets[@]}.
  • The program will print to screen a randomly selected 'odd numbered' line from a randomly selected file.
  • Once the line has been printed, I don't want it printed again...

Most of it is fine, but I am having trouble creating arrays based on the contents of ${selected_sets[@]}... I think I have got my syntax all wrong :)

for i in ${selected_sets[@]}
do 
    x=1
    linecount=$(cat $desired_path/$i | wc -l) #get line count of every set

        while [ $x -le $linecount ] 
        do ${i}[${#${i}[@]}]=$x
        x=$(($x+2)) # only insert odd numbers up to max limit of linecount
        done
done

The problem is ${i}[${#${i}[@]}]=$x I know that I can use array[${#array[@]}]=$x but I don't know how to use a variable name.

Any ideas would be most welcome (I am really stumped)!!!

Triad sou.
  • 2,969
  • 3
  • 23
  • 27
beoliver
  • 5,579
  • 5
  • 36
  • 72
  • Why do you want to name the variables? If you want to access the arrays again later, you can store these in a doubly subscripted array, which you can declare outside the for loop. – Niel de Wet Oct 14 '11 at 10:01
  • I have only been using bash arrays for about a week, so my reasoning was based on the fact that I thought this would be the best way to achieve what I wanted... doubly subscripted arrays are new to me... I'll give them a read and see if they do what I want. Thanks for the heads up! – beoliver Oct 14 '11 at 10:27
  • P.S - any idea of online documentation? – beoliver Oct 14 '11 at 11:03
  • I like to use http://ss64.com/bash/ for most of my bash questions. – Niel de Wet Oct 14 '11 at 11:37

2 Answers2

2

In general, this type is question is solved with eval. If you want a a variable named "foo" and have a variable bar="foo", you simply do:

eval $bar=5

Bash (or any sh) treats that as if you had typed

foo=5

So you may just need to write:

eval ${i}[\${#${i}[@]}]=$x

with suitable escapes. (A useful technique is to replace 'eval' with 'echo', run the script and examine the output and make sure it looks like what you want to be evaluated.)

William Pursell
  • 204,365
  • 48
  • 270
  • 300
1

You can create named variables using the declare command

declare -a name=${#${i}[@]}

I'm just not sure how you would then reference those variables, I don't have time to investigate that now.

Using an array:

declare -a myArray

for i in ${selected_sets[@]}
do 
x=1
linecount=$(cat $desired_path/$i | wc -l) #get line count of every set

    while [ $x -le $linecount ] 
    do
    $myArray[${#${i}[@]}]=$x
    let x=x+1 #This is a bit simpler!
    done
done

Beware! I didn't test any of the above. HTH

Niel de Wet
  • 7,806
  • 9
  • 63
  • 100