mozerella
mozerella

Reputation: 39

Bash script to find files in a list, copy them to dest, print files not found

I would like to build on the answer I found here: Bash script to find specific files in a hierarchy of files

find $dir -name $name -exec scp {} $destination \;

I have a file with a list of file names and I need to find those files on a backup disk, then copy those files found to a destination folder, and lastly print the files that could not be found to a new file.

the last step would be helpful so that I wouldn't need to make another list of files copied and then do a compare with original list.

If the script can then make a list of the copied files, and do a compare, then print the differences, then that's exactly what's required. Unless the shell process find can print to file each time it "Can't find" a file.

Upvotes: 1

Views: 9312

Answers (2)

Navaneeth Krishnan M
Navaneeth Krishnan M

Reputation: 141

Assuming that your list is separated by newlines; something like this should work

#!/bin/bash

dir=someWhere
dest=someWhereElse
toCopyList=filesomewhere
notCopied=filesomewhereElse

while read line; do
   find "$dir" -name "$line" -exec cp '{}' $dest \; -printf "%f\n"     
done < "$toCopyList" > cpList

#sed -i 's#'$dir'/##' cpList
# I used # instead of / in sed to not confuse sed with / in $dir
# Also, I assumed the string in $dir doesnot end with a /

cat cpList "$toCopyList" | sort | uniq -c | sed -nr '/^ +1/s/^ +1 +(.*)/\1/p' > "$notCopied"
# Will not work if you give wild cards in your "toCopyList"

Hope it helps

Upvotes: 2

Zsolt Botykai
Zsolt Botykai

Reputation: 51613

while read fname ; do
  find /FROM/WHERE/TO/COPY/ \
       -type f \
       -name "$fname" \
       -exec cp \{\} /DESTINATION/DIR/ \; 2>/dev/null 
  find /DESTINATION/DIR/ \
       -type f \
       -name "$fname" &>/dev/null || \
       echo $fname
done < FILESTOCOPY > MISSEDFILES

Will do.

Upvotes: 0

Related Questions