使用shell脚本或AppleScript

时间:2017-09-18 13:24:07

标签: shell zip applescript

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

我的文件夹结构如下:

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

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

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

我猜那里有人必须知道如何解决我的存档问题。提前感谢您的建议。

1 个答案:

答案 0 :(得分:0)

经过一番游戏,我想出了以下解决方案:

#!/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的文件夹。与文件夹内指定扩展名匹配的所有文件都在每个文件夹的一个目标存档中压缩。