ventsyv
ventsyv

Reputation: 3532

Script to find and copy files

I want to write a script that looks for a list of files and copies them to another directory:

for file in `cat ~/fileNames.txt`; do cp $(find $PWD -name $file) $TARGET_DIR; done

Printing out $file works as expected but find is not returning any output in the following script I use for debugging:

for file in `cat ~/fileNames.txt`; do echo $file; echo $(find $PWD -name $file); done

I know that the files are in one of the sub directories below $PWD

Update:

Using the -exec option only copies the last file in the list.

for file in `cat ~/fileNames.txt`; do find $PWD -name "$file" -exec cp -f {} $TARGET_DIR \;; done

Using while loop does not seem to be doing anything different:

cat ~/fileNames.txt | while read file; do echo $file; find $PWD -name "$file" -exec cp -f {} $TARGET_DIR \;; done

Any ideas?

Upvotes: 0

Views: 542

Answers (2)

gniourf_gniourf
gniourf_gniourf

Reputation: 46903

Never do this:

for file in `cat ~/fileNames.txt`; do

It's subject to word splitting and pathname expansion. Instead you'll want to read your file with a while loop:

while IFS= read -r file; do
    # stuff
done < ~/fileNames.txt

Then you can use find with its -exec action:

find . -name "$file" -exec cp {} "$target_dir" \;

So that finally:

while IFS= read -r file; do
    find . -name "$file" -exec cp {} "$target_dir" \;
done < ~/fileNames.txt

Upvotes: 0

anubhava
anubhava

Reputation: 786359

Try this script:

while read -r file; do
   find . -name "$file"
done < ~/fileNames.txt

And to copy files:

while read -r file; do
   find . -name "$file" -exec cp {} "$TARGET_DIR" \;
done < ~/fileNames.txt

Upvotes: 1

Related Questions