如果系统存在文件名相同,但路径不同的文件,如果单纯用find来批量复制到一个地方的话会被覆盖掉,下面的脚本是实现根据文件名的路径来进行存放复制。为能更好的测试,脚本中加了在不同路径创建相同文件名的程序。

  1. #!/bin/sh
  2. . /etc/profile
  3. # define
  4. tf=testfile
  5. destpath=/root/found
  6. [ ! -d $destpath ] && mkdir -p $destpath
  7. # touch some the same file for test
  8. TouchFile()
  9. { 
  10. echo "/tmp" > /tmp/$tf
  11. echo "/home" > /home/$tf
  12. echo "/root" > /root/$tf
  13. echo "/var/tmp" > /var/tmp/$tf
  14. }
  15. # find the file and copy to the dest dir
  16. FindCopy()
  17. {
  18. TouchFile
  19. if [ $? -eq 0 ];then
  20.     for i in $(find / -name $tf);do
  21.         [ ! -d $destpath/$(dirname $i) ] && mkdir -p $destpath$(dirname $i)
  22.         cp -rf $i $destpath$(dirname $i) 
  23.         #echo $i
  24.     done
  25. else
  26.     echo "please touch some test file first..."
  27. fi
  28. }
  29. FindCopy