【问题标题】:Compress all files of certain file types in subfolders in one file per subfolder using shell script or AppleScript使用 shell 脚本或 AppleScript 将子文件夹中特定文件类型的所有文件压缩到每个子文件夹一个文件中
【发布时间】:2017-09-18 13:24:06
【问题描述】:

我正在寻找一种将特定文件类型的所有文件归档在每个子文件夹的一个 zip 文件中的方法。


我的文件夹结构如下:

/path/to
    └── TopLevel
        ├── SubLevel1
        │   ├── SubSubLevel1
        │   ├── SubSubLevel2
        │   └── SubSubLevel3
        ├── SubLevel2
        │   ├── SubSubLevel1
        │   ├── SubSubLevel2
        │   └── SubSubLevel3
        ├── SubLevel3
        │   ├── SubSubLevel1
        │   └── SubSubLevel2
        └── SubLevel4

在每个文件夹或子文件夹或子子文件夹中,有文件类型为 *.abc、*.xyz 以及 *.001 到 *.999 的文件,我想将所有这些文件压缩成每个文件夹一个 zip 文件,即“TopLevel”的“SubLevel1”的“SubSubLevel1”文件夹中的所有指定类型的文件应打包到“SubSubLevel1”文件夹内名为“SubSubLevel1_data.zip”的一个文件中。这些文件夹中与上述搜索条件不匹配的所有其他文件都应解压缩到同一目录中。

我找到了一些想法 herehere,但是这两种方法都基于不同的文件归档方式,由于我不是很有经验,所以到目前为止我还没有找到一种方法来满足我的需求使用 shell 脚本。我也尝试过使用 AppleScript 获得解决方案,但我面临的问题是如何获取文件夹中的所有文件,并将数字作为扩展名(*.001 到 *.999)。使用 RegEx,我会执行类似 ".abc|.xyz.\d\d\d" 之类的操作,这将涵盖我对某些文件类型的搜索,但我现在也不确定如何在 AppleScript 中实现 grep 的结果。

我想肯定有人知道如何解决我的归档问题。提前感谢您的建议。

【问题讨论】:

    标签: shell zip applescript


    【解决方案1】:

    经过一番玩弄后,我想出了以下解决方案:

    #!/bin/bash
    
    shopt -s nullglob
    
    find -E "$PWD" -type d -maxdepth 1 -regex ".*201[0-5][0-1][0-9].*" -print0 | while IFS="" read -r -d "" thisFolder ; do
      echo "The current folder is: $thisFolder"
      to_archive=( "$thisFolder"/*.[Aa][Bb][Cc] "$thisFolder"/*.[Xx][Yy][Zz] "$thisFolder"/*.[0-9][0-9][0-9] )
    
      if [ ${#to_archive[@]} != 0 ]
      then
        7z a -mx=9 -uz1 -x!.DS_Store "$thisFolder"/"${thisFolder##*/}"_data.7z "${to_archive[@]}" && rm "${to_archive[@]}"
      fi
    
      find "$thisFolder" -type d -mindepth 1 -maxdepth 1 -print0 | while IFS="" read -r -d "" thisSubFolder ; do
        echo "The current subfolder is: $thisSubFolder"
        to_archive=( "$thisSubFolder"/*.[Aa][Bb][Cc] "$thisSubFolder"/*.[Xx][Yy][Zz] "$thisSubFolder"/*.[0-9][0-9][0-9] )
    
        if [ ${#to_archive[@]} != 0 ]
        then
          7z a -mx=9 -uz1 -x!.DS_Store "$thisSubFolder"/"${thisSubFolder##*/}"_data.7z "${to_archive[@]}" && rm "${to_archive[@]}"
        fi
      done
     done
    

    我的脚本有两个嵌套的 for 循环来遍历子文件夹和子子文件夹。通过“查找”,我寻找一个正则表达式模式,以便仅备份 2010-2015 的文件夹。文件夹内与指定扩展名匹配的所有文件都被压缩到每个文件夹的一个目标存档中。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-04
      • 1970-01-01
      • 2017-10-27
      • 2018-10-05
      • 2015-11-22
      相关资源
      最近更新 更多