tags:

views:

61

answers:

3

Hi sorry for asking simple shell question again but my TA in school doesnt check the school forum so I never get any answer, please help me again, thanks

anyways:

I am trying to use array to store a list of file names using the Find command, but for some reason the array fail 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?

+2  A: 

You could use something like that:

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

E.g. make a copy:

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

HTH

Johannes Weiß
thanks a lot!! it worked and i learned something new
Shellscriptbeginner
Using a `for` loop is definitely a better choice here. Using an array would work except that it reads the entire list into a variable and then iterates over the variable. This version reads each file name as it comes from `find` and processes it inline.
D.Shawley
D.Shawley, could you please post a sample with a for loop? It should work for files with spaces in the name as well, I think.
Johannes Weiß
+1  A: 
#!/bin/sh
PATH="/some/dir"
COPY_PATH="/some/other/dir"
find ${PATH} -name "*.txt" | while read line; do
    cat $line
    cp $line ${COPY_PATH}
done

And the reason it's not working in school is probably because the school is using an older bash version, this however works in all versions.

EDIT: I did not see Johannes Weiß post, please refer to that.

Anders
thankyou for your reply too
Shellscriptbeginner
+1  A: 
find . -name '*.txt' | while IFS= read -r FILE; do
    echo "Copying $FILE.."
    cp "$FILE" /destination
done
ghostdog74