gpt4 book ai didi

linux - 移动未使用的文件并保留目录结构

转载 作者:太空狗 更新时间:2023-10-29 12:39:13 26 4
gpt4 key购买 nike

我正在尝试从不断写入(文件和文件夹)的源文件夹中移动文件。一旦文件不再被写入,它就不会再被读/写。我想将未使用的文件移动到另一个文件夹,但保留目录结构。我最终会想将它添加到一个连续的循环中,或者让它定期运行以“清理”源文件夹。

这是我之前和之后的例子:

Before:
Parent/
├── Source/
│ ├── DirA/
│ │ ├── File1InUse.abc
│ │ ├── File2NotInUse.abc
│ │ └── File3InUse.abc
│ └── DirB/
│ ├── File4InUse.abc
│ ├── File5NotInUse.abc
│ └── File6NotInUse.abc

├── Destination/

After:
Parent/
├── Source/
│ ├── DirA/
│ │ ├── File1InUse.abc
│ │ └── File3InUse.abc
│ └── DirB/
│ └── File4InUse.abc

├── Destination/
├── DirA/
│ └── File2NotInUse.abc
└── DirB/
├── File5NotInUse.abc
└── File6NotInUse.abc

我找到了 answers移动未使用的文件的文件:

comm -2 -3 <(find $dir -maxdepth 1 -type f|sort) <(sudo lsof $dir/* | awk '(NR>1) {print $9}'|sort) | xargs -I {} mv {} $move_dir

我还找到了answers移动文件并保留目录结构:

也许与rsync:

rsync -axuv --delete-after --progress Source/ Target/

我不太了解命令行,所以我不确定如何将这两个概念放在一起。

感谢您的帮助。

最佳答案

这就是我要做的。创建一个脚本,以便您可以从其他程序或 cron 作业中使用它。

#! /bin/bash

isUsed() {
test -w "$1" && echo 1 || echo 0
}

parent_dir=$1
src_dir=$2
dst_dir=$3

while read -r line
do
retval=$(isUsed "$line")
if [ $retval -eq "0" ]
then
filepath=$(dirname $line)
filepath=${filepath#$parent_dir}
filepath=${filepath#$src_dir}
mkdir -p "$parent_dir$dst_dir$filepath"
mv "$line" "$parent_dir$dst_dir$filepath"/
fi
done <<< $(find "$parent_dir$src_dir")

用法

./script.sh Parent/ Source/ Destination/

工作

  1. isUsed 函数用于检查文件当前是否正在使用。

    返回值:1 - 文件正在使用,0 - 文件未被使用

    目前,文件权限用于查找文件是否在使用中。如果一个文件有写权限,那么它被认为是被使用的。您可以将其更改为任何其他逻辑以评估是否使用了文件,例如问题中提到的 lsof

  2. find "$parent_dir$src_dir" 将列出给定路径中的所有文件和目录。使用 while 循环将 find 命令的输出一次一个读入 $line

    示例:假设 $line 等于 Parent/Source/DirA/File2NotInUse.abc

  3. 我们调用isUsed 函数来检查文件是否正在使用。函数调用的返回值存入$retval

  4. 如果 $retval 等于 "0",则表示该文件未被使用,我们必须将其移动到目标目录。

  5. 首先,我们将使用dirname 生成要移动的文件的路径。它将返回文件的相对路径。

    $filepath 等于 Parent/Source/DirA

    然后我们从文件路径中删除父目录名。

    因此 $filepath 变成了 Source/DirA

    然后我们从 filepath 中删除源目录名称。

    因此 $filepath 现在等于 DirA。生成的 filepath 将是文件相对于源目录的路径。

  6. 使用给定的文件路径Destination/ 中创建一个目录。 mkdir -p 将创建所有在 filepath 中给定的中间目录。

    mkdir -p Parent/Destination/DirA

  7. 最后一步是将实际文件从其 Source 路径移动到新创建的 Destination 路径。

    mv Parent/Source/DirA/File2NotInUse.abc Parent/Destination/DirA/

关于linux - 移动未使用的文件并保留目录结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54996098/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com