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?
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?
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.