Bash 脚本在列表中查找文件,将它们复制到 dest,打印未找到的文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16025439/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 05:11:48  来源:igfitidea点击:

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

linuxbashfind

提问by mozerella

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

我想以我在这里找到的答案为基础: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.

如果脚本随后可以制作复制文件的列表,并进行比较,然后打印差异,那么这正是所需要的。除非 shell 进程 find 每次“找不到”文件时都可以打印到文件。

回答by Navaneeth Krishnan M

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 +(.*)//p' > "$notCopied"
# Will not work if you give wild cards in your "toCopyList"

Hope it helps

希望能帮助到你

回答by Zsolt Botykai

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.

会做。