0

Suppose I have this code:

for i in $(find * -type f -name "*.txt"); do 
  # echo [element by it's index]
done

How do I access, if possible, an element by it's index?

schrodingerscatcuriosity
  • 12,087
  • 3
  • 29
  • 57
  • 1
    Where and how you define this array? – Romeo Ninov Mar 09 '20 at 14:25
  • @RomeoNinov Sorry I'll try to make the question more clear. I just put `${array[0]}` as an example on how it's done if you would loop an array. What I'm asking is what would be in place of it in the above code. – schrodingerscatcuriosity Mar 09 '20 at 14:28
  • 2
    The safest way to do this (to do _something_ on the things that `find` finds) is through letting `find` [execute the loop through `-exec`](https://unix.stackexchange.com/questions/389705), not by [looping over the output of `find`](https://unix.stackexchange.com/questions/321697). – Kusalananda Mar 09 '20 at 14:36

1 Answers1

2

Your command

$(find * -type f -name "*.txt")

will return a (space-separated) bash list, not an array, hence you cannot really access the individual elements in a "targeted" way.

To convert it to a bash array, use

filearray=( $(find * -type f -name "*.txt") )

(note the spaces!)

Then, you can access the individual entries as in

for ((i=0; i<n; i++))
do
   file="${filarray[$i]}"
   <whatever operation on the file>
done

where the number of entries can be retrieved via

n="${#filearray[@]}"

Note however that this only works if your file-names don't contain special characters (in particular space) and hence, once again, parsing the output of ls or find is not recommended. In your case, I would recommend seeing if the -exec option of find can do what you need to accomplish.

AdminBee
  • 21,637
  • 21
  • 47
  • 71