How can I process the results of find in a bash script?

I'm trying to use an array to store a list of file names using the find command.

For some reason the array fails to work in the bash used by the school, my program works on my own laptop though.

So I was wondering if there's another way to do it, this is what i have:

array = (`find . -name "*.txt"`)  #this will store all the .txt files into the array

Then I can access the array items and make a copies of all the files using the cat command.

Is there another way to do it without using an array?


Solution 1:

You could use something like this:

find . -name '*.txt' | while read line; do
    echo "Processing file '$line'"
done

For example, to make a copy:

find . -name '*.txt' | while read line; do
    echo "Copying '$line' to /tmp"
    cp -- "$line" /tmp
done

Solution 2:

I was having issue with Johannes Weiß's solution, if I was just doing an echo it would work for the full list of files. However, if I tried running ffmpeg on the next line the script would only process the first file it encountered. I assumed some IFS funny business due to the pipe but I couldn't figure it out and ran with a for loop instead:

for i in $(find . -name '*.mov' ); 
do
    echo "$i"
done

Solution 3:

I think starpause has the cleanest solution, however it fails when there is whitespaces in paths. This is fixed by setting IFS. The correct answer is therefore:

IFS=$'\n'
for i in $(find . -name '*.mov' ); 
do
    echo "$i"
done
unset IFS

You unset IFS in order to reset behaviour for IFS and as to why the $ is needed in IFS=$'\n', see https://unix.stackexchange.com/questions/184863/what-is-the-meaning-of-ifs-n-in-bash-scripting