3

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+" 
  • 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
8

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
  • 4
    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 7 '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 1:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.