给定父目录的所有子目录中的 zip 文件

给定父目录的所有子目录中的 zip 文件

假设我有一个parent_directory/包含以下子目录的child1/,child2/child3/.

如何编写脚本将zip所有*.txt文件写入childx/childx.zip 我也希望它childx.zip位于其childx/目录中。

答案1

样本数据

$ mkdir -p parent_directory/child{1..3}
$ touch parent_directory/child{1..3}/file1.txt
$ touch parent_directory/child{1..3}/file2.txt

$ tree parent_directory/
parent_directory/
├── child1
│   ├── file1.txt
│   └── file2.txt
├── child2
│   ├── file1.txt
│   └── file2.txt
└── child3
    ├── file1.txt
    └── file2.txt

3 directories, 6 files

解决方案

现在编写 zip 文件的脚本:

$ cd parent_directory/; for i in *; do find ${i} -name "*.txt" -print | zip ${i}.zip -@; mv ${i}.zip ${i}; done; cd -
  adding: child1/file2.txt (stored 0%)
  adding: child1/file1.txt (stored 0%)
  adding: child2/file2.txt (stored 0%)
  adding: child2/file1.txt (stored 0%)
  adding: child3/file2.txt (stored 0%)
  adding: child3/file1.txt (stored 0%)

结果

结果:

$ tree parent_directory/
parent_directory/
├── child1
│   ├── child1.zip
│   ├── file1.txt
│   └── file2.txt
├── child2
│   ├── child2.zip
│   ├── file1.txt
│   └── file2.txt
└── child3
    ├── child3.zip
    ├── file1.txt
    └── file2.txt

3 directories, 9 files

$ unzip -l parent_directory/child1/child1.zip
Archive:  parent_directory/child1/child1.zip
  Length      Date    Time    Name
---------  ---------- -----   ----
        0  07-05-2018 10:08   child1/file2.txt
        0  07-05-2018 10:08   child1/file1.txt
---------                     -------
        0                     2 files
$ unzip -l parent_directory/child2/child2.zip
Archive:  parent_directory/child2/child2.zip
  Length      Date    Time    Name
---------  ---------- -----   ----
        0  07-05-2018 10:08   child2/file2.txt
        0  07-05-2018 10:08   child2/file1.txt
---------                     -------
        0                     2 files
$ unzip -l parent_directory/child3/child3.zip
Archive:  parent_directory/child3/child3.zip
  Length      Date    Time    Name
---------  ---------- -----   ----
        0  07-05-2018 10:08   child3/file2.txt
        0  07-05-2018 10:08   child3/file1.txt
---------                     -------
        0                     2 files

参考

答案2

尝试,

$ zip -R parent_directory '*.txt'

相关内容