同时移动 2 次时如何指向特定文件?Unix

  • 本文关键字:文件 Unix 何指 移动 bash unix
  • 更新时间 :
  • 英文 :


我正在尝试将(使用 mv(多个文件从文件夹 A 移动到文件夹 B。我还将(文件名、文件路径、文件创建日期、文件大小(写入单独的.txt文件。

我的问题是:有时文件可能具有不同的权限,当您尝试移动具有不正确权限的文件时,脚本将运行,但文件实际上不会被移动。现在我只想写从文件夹 A 移动到文件夹 B 的文件(文件名、文件路径、文件创建日期、文件大小(。

例如:

文件夹 A 包含:文件 1、文件 2、文件 3

脚本之后

文件夹 B 包含:文件 1、文件 2

".txt"文件应仅包含文件 1 和 File2 的元数据。

我不能直接指向文件夹 B,因为随着时间的推移,更多的文件将被移动到此文件夹中,.txt文件应仅包含移动的最新文件的元数据。

我当前的脚本仍然抓取 FolderA 中的所有内容,我只想能够抓取被移动的脚本。

提前感谢您的帮助!

#!/bin/bash
base_dir="FolderA"
target_dir="FolderB"

find $base_dir -type f -name '*837*' -printf '%C@t%pn'| sort -nk1 | cut -f2- | while IFS= read -r file;do
year="$(date -d "$(stat -c %z "$file")" +%Y)"
month="$(date -d "$(stat -c %z "$file")" +%m)"
day="$(date -d "$(stat -c %z "$file")" +%d)"
mv --backup=t "$file" "$target_dir/$year/$month/$day";
echo "$(basename "$file")"  >> "$target_dir/test_file.txt";
echo | stat -c %z "$file" >> "$target_dir/test_file.txt";
echo     "$file"  >> "$target_dir/test_file.txt";
echo     "$target_dir/$year/$month/$day" >> "$target_dir/test_file.txt";
echo | stat -c %s "$file" >> "$target_dir/test_file.txt";

done

同时移动 2 次时如何指向特定文件?

由于您不是同时移动多个文件,而是在while循环中一个接一个地移动,因此这个问题是没有根据的。

.txt文件应仅包含移动的最新文件的元数据。

总结Charles Duffy对移动部分的相关建议,并进一步简化日期处理(因为您不需要分别使用年,月和日(:

… | while IFS= read -r file; do
date=$(date -d "$(stat -c %z "$file")" +%Y/%m/%d)
target_path="$target_dir/$date"
mkdir -p "$target_path" # Wasn't this missing?
if mv --backup=t "$file" "$target_path"; then
stat --printf="${file##*/}n%zn$filen$target_pathn%sn" "$target_path/${file##*/}"
fi
done >"$target_dir/test_file.txt"

这也利用了 Bash 的参数扩展${file##*/}而不是basename

最新更新