【问题标题】:Copy latest modified file from all subdirectories to a new directory having same sub directory structure [closed]将所有子目录中的最新修改文件复制到具有相同子目录结构的新目录[关闭]
【发布时间】:2017-09-19 05:55:51
【问题描述】:

我有一个包含 100 个子目录的目录,每个子目录有 100 个文件。每个子目录中的文件数量每天都增加一个。我想在 Linux 中编写一个脚本,将所有 100 个子目录复制到另一个位置,每个子目录只有一个最新文件。如何做到这一点?

【问题讨论】:

标签: linux bash rsync cp


【解决方案1】:

从您的当前目录(有 100 个子目录)中,您可以将脚本运行为:

   for f in `find ./* -maxdepth 0 -type d`
do
        if [ $f != "./directory_to_copy" ]
        then
                  cp $f/`ls -t $f | head -1` ./directory_to_copy
        fi
 done

如果您的out目录不在当前目录中,您可以跳过If语句,您可以在cp语句中指定需要存储的目录的相对路径或绝对路径,名称为:

cp $f/`ls -t $f | head -1` path_to_directory/name_of_directory

【讨论】:

  • 谢谢。这会复制每个子目录中的所有最新文件,但会将它们放在单个输出目录中。有没有办法在 out 目录中保持相同的目录结构以包含所有 100 个子目录,每个子目录都包含单个最新文件。
  • 可以修改 if 块为:if [ $f != "./directory_to_copy" ] then mkdir ./directory_to_copy/$f 2>/dev/null cp $f/ls -t $f | head -1` ./directory_to_copy/$f fi` 如果 out 目录不在当前目录中:mkdir path_to_directory/name_of_directory/$f 2>/dev/null cp $f/ls -t $f | hecad -1` path_to_directory/name_of_directory/$f`
【解决方案2】:

你可以修改 if 块为:

if [ $f != "./directory_to_cop" ]
    then
              mkdir ./directory_to_copy/$f 2>/dev/null
              cp $f/`ls -t $f | head -1` ./directory_to_copy/$f
    fi

如果 out 目录不在当前目录中:

mkdir path_to_directory/name_of_directory/$f 2>/dev/null

cp $f/`ls -t | head -1` path_to_directory/name_of_directory/$f

【讨论】:

    猜你喜欢
    • 2013-06-25
    • 2019-11-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-26
    • 2012-04-08
    • 1970-01-01
    • 2020-12-23
    • 1970-01-01
    相关资源
    最近更新 更多