【发布时间】:2016-07-02 13:18:11
【问题描述】:
在 Unix 中是否有任何命令可以将除最新时间戳文件之外的所有文件从一个目录复制到另一个目录。
Dir1 - 文件 1、文件 2、文件 3、文件 4(新时间戳)
cp 到 Dir2 - file1,file2,file3,我不想要 file4,因为这是 Dir1 中的新文件。
【问题讨论】:
在 Unix 中是否有任何命令可以将除最新时间戳文件之外的所有文件从一个目录复制到另一个目录。
Dir1 - 文件 1、文件 2、文件 3、文件 4(新时间戳)
cp 到 Dir2 - file1,file2,file3,我不想要 file4,因为这是 Dir1 中的新文件。
【问题讨论】:
#!/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
【讨论】:
您可以使用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
【讨论】:
ls 为您提供可解析的信息。此外,在使用变量时,您应该始终引用它们。最后,您没有检查涉及子目录的情况。
ls?请解释 cp 命令确实应该被引用。