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

Viewed 87330

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?

7 Answers

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
find . -name '*.txt' | while IFS= read -r FILE; do
    echo "Copying $FILE.."
    cp "$FILE" /destination
done

One more variant to change some variable inside while loop which uses subshell

concat=""

while read someVariable
do
    echo "someVariable: '$someVariable'"
    concat="$concat someVariable")
done < <(find "/Users/alex" -name "*.txt")

echo "concat: '$concat'"

Generalized version tested with whitespace

echo $BASH_VERSION
4.2.46(2)-release

Make some horrible looking directories and files

mkdir "spaces test"
cd spaces\ test/
touch 'test one'{1..5}
touch 'testone'{1..5}
mkdir test\ two
cd test\ two/
touch 'test one'{1..5}

Create and run the script

set -u
while read -r line
do
    echo "$line"
done < <(find "spaces test" -type f)
Related