如何在保持文件夹结构的同时复制在过去一天内修改过的文件?

时间:2019-04-30 13:13:09

标签: bash scripting

我正在尝试仅将在过去一天中发生更改的数据从一个目录复制到另一个目录。复制数据后,我想保持文件夹结构。例如/nas/data/dir1/file.txt更改,我希望创建/destination/data/dir1/file.txt。我得到的最接近的是下面。

我发现的主要问题是,修改其中的文件内容后,文件夹上的mtime不会更新。我也相信,当触发复制时,它将复制已修改文件夹中的所有文件。

find /NAS/data/dir1 -type d -mtime -1 -exec cp -rt /mnt/dest/dir1 {} +

1 个答案:

答案 0 :(得分:0)

您的查找将查找目录(-d型)而不是文件(-f型)。因为您只想复制深层目录结构中的某些文件,所以我认为您无法通过简单的find ... -exec来做到这一点(因为cp需要目的地中的目录结构)。这是一个示例脚本(带有注释),您可以使用:

# create a reftime (for the last 24h)
((reftime=$(date '+%s')-(24*60*60)))
# create a reffile for that time in /var/tmp (or any other place)
reffile=/var/tmp/reffile.$$.tmp
touch --date=@${reftime} ${reffile}

# find all files (in srcbase), that was changed in the last 24h - that means 
# now all files that are newer then our reffile, and copy to destbase...
srcbase=/NAS/data/dir1
destbase=/mnt/dest/dir1
# for all of these files we need the directory names (because we need the structure for copy)
chgfiles=/var/tmp/chgfile.$$.tmp
find ${srcbase} -type f -newer $reffile 2>/dev/null | sort -u >${chgfiles}

# now you have a file list that you must cp (or print or whatever)
cat ${chgfiles} | while read f ; do
  dest=$(dirname $(echo "$f" | sed -e "s#${srcbase}#${destbase}#"))
  echo "copy file $f to destination $dest ..."
  # create directory structures if not exist
  mkdir -p "${dest}"
  # and finaly cp the file
  cp "${f}" "${dest}/"
done

# clear all tmp files
rm ${reffile} ${chgfiles}