0

Say I have a parent_directory/ with the following sub-directories child1/, child2/ and child3/.

How do I script to zip all *.txt files in childx/ into childx.zip I also want this childx.zip to be located in its childx/ directory.

0

Sample data

$ 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

Solution

Now to script the zip files:

$ 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%)

Results

And the results:

$ 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

References

  • follow-up question: child1/ has additional sub-directories (and these might have sub-directories too), and I'd like the script to do the same on these sub-directories as well, recursively. Would a simple -r do it? and where would I place it in the command? – Tejas Jul 5 '18 at 14:27
0

Try,

$ zip -R parent_directory '*.txt'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.