【问题标题】:Unix scipt to copy all the files except latest timestamp file用于复制除最新时间戳文件之外的所有文件的 Unix 脚本
【发布时间】:2016-07-02 13:18:11
【问题描述】:

在 Unix 中是否有任何命令可以将除最新时间戳文件之外的所有文件从一个目录复制到另一个目录。

Dir1 - 文件 1、文件 2、文件 3、文件 4(新时间戳)

cp 到 Dir2 - file1,file2,file3,我不想要 file4,因为这是 Dir1 中的新文件。

【问题讨论】:

    标签: bash shell unix sh


    【解决方案1】:
    #!/bin/bash
    dir1=/first/dir
    dir2=/second/dir
    
    # first loop through and find oldest file
    # http://mywiki.wooledge.org/BashFAQ/003
    unset -v newest
    for file in "$dir1"/*; do
        [[ -f "$file" ]] && [[ "$file" -nt "$newest" ]] && newest="$file"
    done
    
    # then loop through and perform actions on the others
    for file in "$dir1"/*; do
        if [[ -f "$file" ]] && [[ ! "$file" == "$newest" ]]; then
            cp -p "$file" "$dir2"
        fi
    done
    

    【讨论】:

      【解决方案2】:

      您可以使用ls -1tr | tail -1 构造来获取最新文件。

      然后复制文件,最新的除外。

      如果文件列表通常很短,则可以更改此代码 创建一个文件列表,然后进行复制——这样会更有效率。

      dir2="../somewhereelse"
      exception=$(ls -1tr | tail -1)
      for fn in *; do
        if [[ $fn == $exception ]]; then
          continue
        fi
        cp "$fn" "$dir2"
      done
      

      【讨论】:

      • You should not rely on ls 为您提供可解析的信息。此外,在使用变量时,您应该始终引用它们。最后,您没有检查涉及子目录的情况。
      • 为什么不应该依赖ls?请解释 cp 命令确实应该被引用。
      • 我的评论中有一个链接。简而言之,您会惊讶于文件名中的有效字符类型。
      • 除非这是针对最终用户的脚本,否则我通常假设客户端对其环境有一些控制,并且通常不会生成垃圾文件名。
      猜你喜欢
      • 2015-01-02
      • 2013-04-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-01
      相关资源
      最近更新 更多