5

I am a newbie in Unix. I have a requirement in which I have to put the output of find statement in array because later in the script I have to use the output lines one by one. My find statement will retrieve me the location of directories based on the condition.

Here are the find statements:

find blah -mindepth 3 -maxdepth 3 -type d  -regex ".*/V[0-9]+/wsdls+" 
Wuffers
  • 19,241
Ankit
  • 61
  • i got a solution for this.. array=($(find blah -mindepth 3 -maxdepth 3 -type d -regex ".*/V[0-9]+/wsdls+"))

    i=0 for file in "${array[@]}" do echo "${file}" let i++ done but here the strange thing is after executing this though i am able to see data properly but in every line it's saying i++ is not a valida command..and as soon as i removed the i++, then it gave me the data properly..my question is how it is happening as we are not increasing the value of i..

    – Ankit Apr 20 '11 at 12:10
  • If you found an answer, please post it as an actual answer and not a comment. – Wuffers Apr 20 '11 at 12:20
  • hard to give you help when we can't see the newlines in your code. Please put it in an answer. – glenn jackman Apr 20 '11 at 13:21

2 Answers2

11

You can do this:

array=( $(find blah -mindepth 3 -maxdepth 3 -type d -regex ".*/V[0-9]+/wsdls+") )

# loop over it
for i in ${array[@]}
do
    echo $i
done

# or in a while loop
i=0;
while [ $i -lt ${#array[@]} ]
do
    echo $i: ${array[$i]}
    ((i++))
done
dogbane
  • 4,566
  • 6
    You'll need to set IFS=$'\n' first though: in case any of the filenames have spaces, you want to keep them as a single array element. The you'll also want to use double quotes when referencing the array: for i in "${array[@]}" – glenn jackman Apr 20 '11 at 13:15
  • 1
    This is quite old, but this should have been the accepted answer. It works out quite well, and the comment from @glennjackman is also quite useful. – casper Sep 07 '18 at 16:31
  • 1
    A clarification to @glennjackman's answer is that the IFS=$'\n' needs to be at the start of the assignment statement, not in the find subshell; e.g. IFS=$'\n' array=(...). – devstuff Nov 13 '18 at 01:30
1

This answer on stackoverflow has all the details and also some alternatives. But essentially, a reliable way to do it is:

array=()
while IFS=  read -r -d $'\0'; do
    array+=("$REPLY")
done < <(find Where What... -print0)

Using -print0 for the output of find and a null byte as delimiter for read avoids all the pitfalls created by filenames with spaces or worse.

And to iterate over the filenames in the array, use quotes around the array :

for file in "${array[@]}"; do
    echo "$file"
done 
mivk
  • 3,726