如何将目录中的所有文件移动到另一个目录,但复制最新的文件?

如何将目录中的所有文件移动到另一个目录,但复制最新的文件?

我正在尝试编写一个备份脚本,该脚本可移动目录中的所有文件,但仅复制最新修改/最新的文件。

我遇到了一些麻烦,我无法返回正确的最新文件,因为我认为我无法获取findls列出修改后的文件,并且也仅输出文件名。所以我的$latestfile最终会成为一个不同的文件。

帮助?

我当前的代码:

# Primary Backup Location
BACKUP_LOCATION=/my/backup/dir

# List latest file
latestfile=$(find ${BACKUP_LOCATION} -maxdepth 1 -mindepth 1 -type f -exec basename {} \; | sort -nr | awk "NR==1,NR==1 {print $2}")

echo "Latest file is $latestfile"

# List all (EXCEPT LAST) files and get ready to Backup
echo "Backing up all files except last"
for file in $(find ${BACKUP_LOCATION} -maxdepth 1 -mindepth 1 -type f \! -name "$latestfile" -printf "%f\n" | sort -nr )
do
    echo $file
    #mv $file /some/target/dir/$file
done


答案1

弄清楚如何进行这项工作。这是我的备份脚本的一部分,希望有人会发现它有用。

# Location to Backup from
BACKUP_TARGET="/my/dir/to/backup"
# Location to Backup to
BACKUP_LOCATION="/my/backup/store"

# List latest file
file_latest=$(find ${BACKUP_TARGET} -maxdepth 1 -mindepth 1 -printf '%T+ %p\n' | sort -r | head -n 1 | sed 's|.*/||' )
echo "Latest file is $file_latest"

# List the rest of files
file_rest_of_em=$(find ${BACKUP_TARGET} -maxdepth 1 -mindepth 1 -type f \! -name "$file_latest" | sed 's|.*/||' )

# make newlines the only separator
IFS=$'\n'

# Backup all previous Backups, MOVE ALL
echo "Backing up all files except Latest Backup..."
for file in $file_rest_of_em
do
    echo "Moving $file"
    mv -n ${BACKUP_TARGET}/$file $BACKUP_LOCATION/
done

# Backup Latest Backup, LEAVE COPY BEHIND
if [ -f "$BACKUP_LOCATION/$file_latest" ]; then
    echo "$file_latest (Latest Backup) already exists."
else
    echo "$file_latest (Latest Backup) does not exist."
    echo "Copying $file_latest..."
    cp -n --preserve=all ${BACKUP_TARGET}/$file_latest $BACKUP_LOCATION/
fi

# done with newline shenanegans
unset IFS

感谢您的帮助@Panki

相关内容