Bash - replacing target files with a specific file, spaces in directory names

I have a large tree of file directories and I am using the following script to list and replace the name I am looking for with a specific file. The problem is that I don't know how to write createList () for-loop correctly to account for spaces in the directory name. If all directories have no spaces, it works great.

The output is a list of files, then a list of "cp" commands, but reports directories with spaces in them as separate dirs.

aindex=1
files=( null )

[ $# -eq 0 ] && { echo "Usage: $0 filename" ; exit 500; }

createList(){
    f=$(find . -iname "search.file" -print)
    for i in $f
    do
        files[$aindex]=$(echo "${i}")
            aindex=$( expr $aindex + 1 )
    done
    }

writeList() {
    for (( i=1; i<$aindex; i++ ))
    do
        echo "#$i : ${files[$i]}"
    done
    for (( i=1; i<$aindex; i++ ))
    do
        echo "/usr/bin/cp /cygdrive/c/testscript/TheCorrectFile.file ${files[$filenumber]}"
    done
}

createList
writeList

      

+2


a source to share


1 answer


Replace your entire script with these four lines:

find . -iname "search.file" | while read file
do 
    /usr/bin/cp /cygdrive/c/testscript/TheCorrectFile.file "$file"
done

      



(But not cp

in /bin

? Oh, Cygwin is in both of them. It is more portable, however, to use /bin

.)

+2


a source







All Articles