【问题标题】:tar and recursive archivingtar 和递归归档
【发布时间】:2014-10-27 21:51:11
【问题描述】:

我下面的代码应该递归查找包含 doc/docx 文件的文件夹,并仅归档其路径中的文件夹。当在 tar 中查找时为空。 tar 因 Cowardly 拒绝创建空存档而中断。我使用 -maxdepth 1 来避免它,但不确定这是否是正确的解决方案。另一个问题是 oring 不能按预期工作。如果 notes 存在,则 test 将被忽略。有什么建议? 也欢迎提出一些代码优化建议

for D in $(find . ! -newermt $date1 -ipath "*test*" -or -ipath "*notest*" -iregex ".*\.\(doc\|docx\)" -printf "%h\n" | sort -u)
    do :
    cd $D && tar --no-recursion --ignore-failed-read -czf archive.tar.zip $(find . -maxdepth 1 -iname "*.doc" -or -iname "*.docx" ) --remove-files
    cd ~
done

例子

Test
  |____ test
  |       |___ subtest ___ 1.doc
  |                   |___ 2.doc
  |                   |___ 3.pdf
  |____ notest ___ 1.doc
              |___ 2.docx

预期

Test
  |___ test
  |      |___ subtest ___ archive.tar.zip (contains docs)
  |                  |___ 3.pdf
  |___ notest ___ archive.tar.zip (contains docs)

【问题讨论】:

  • 请注意,.zip 表示您可以使用zip 和unzip 操作的特定类型的存档。对于 gzip 压缩的 tar,习惯上以 .tar.gz 结束文件名。
  • 这是个思路,因为这是一个云存储,可以被不同的站运行不同的操作系统打开。所以不想用工具限制用户。
  • 更改文件名不会更改文件格式。如果要创建 zip 存档,则必须使用可以执行此操作的工具。 Tar 可能不是那个工具。如果您想要在几乎所有类 unix 系统中以相同方式工作的东西,.tar.gz 可能是您的最佳选择。如果您希望与 Windows 兼容,ZIP 可能是更好的选择。无论哪种方式,您都需要合适的工具来完成这项工作。
  • 真实故事。你绝对是对的,但这并不是说实话的全部代码。它是自动执行所有归档和备份的代码的一部分。这是逻辑的总结,但使用的压缩工具是.zip。我的坏我之前没有说清楚。谢谢!

标签: bash recursion find tar


【解决方案1】:

尝试下一个:

arch="archive.tar.gz"
while read -r -d $'\0' dir
do
    (cd "$dir" && find . -maxdepth 1 -iregex '.*\.docx?' -print0 | tar --null -czf "$arch" -T - --remove-files)
    #alternatively
    #(cd "$dir" && shopt -s nocaseglob nullglob && tar --no-recursion -czf "$arch" *.doc *.docx  --remove-files)
done < <(find . \( -ipath '*/test/*' -o -ipath '*/notest/*' \) -iregex '.*\.docx?' -printf '%h\0' | sort -zu)

一些cmets:

  • 替代-ipath与构造\( -ipath '*/test/*' -o -ipath '*/notest/*' \)
  • 正则表达式.*\.docx? - 必须匹配整个文件名,x? 表示零或一x
  • tar 可以使用-T - 从标准输入读取文件列表
  • 使用以空字符结尾的文件名(如果路径包含空格会有所帮助)
  • --null 指示 tar 使用此类以 null 结尾的文件名
  • (cd ... &amp;&amp;)在子shell中运行,所以不需要cd返回

【讨论】:

  • 我部分使用了你的建议,它给出了更好的结果。谢谢
  • @Odin 没问题。无论如何,对我来说,正是你想要的 - 如果你有一些问题,请编辑你的问题......
  • 我怎样才能同时使用-iregex 和-ipath。例如\( -ipath -iregex ".*\.\(test\|notest\) \)"?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多