I have the following directory structure:
/Data
- file 1
- file 2
/Folder1
- file 3
- file 4
/Folder2
- file 5
- file 6
/Folder3
- file 7
- file 8
In Linux I want to zip files (excluding folders) in every directory and create a 7z (or zip) archive in each folder resulting the following:
/Data
Data.7z (Note: this should contain only file1 & 2, not any sub directories)
/Folder1
Folder1.7z (this should contain only file3 & 4, not any sub directories)
/Folder2
Folder2.7z (this should contain only file5 & 6, no Folder3)
/Folder3
Folder3.7z (should contain only file7 & 8)
Following script works in the first directory but not in the sub-directories :
for i in */ ; do base=$(basename “$i”) ; cd $base ; 7za a -t7z -r $base * ; .. ; cd .. ; done;
How can I achieve this?
If you want to use
7z
, the tricky part seems to be persuading it not to recurse; the documentation's indicated-r-
switch appears to be non-functional, and the suggested workaround from the software's author is to exclude subdirectories with the wildcard expression-x!*/
So, given
then
results in
where for example we can check that
Folder2.7z
contains only its own folder's files usingNote:
!*/
may require additional escaping in environments (such as the interactive bash shell) where!
is a history expansion operator.This is untested code, only used with 'echo', since I don't like to end with multiple zip files. And it is phantasy zip syntax, since I don't know 7za, but I will explain:
The script ad-hoc.sh has to be adressed with an absolute path and should not be in the current path, to not affect the outcome, but it might be in the parentdir:
and, if not made executable, be explicitly invoked:
Find shall look in the current dir, only for files of type d (dirs), where to -execute a bashscript with parameter {}, the directory found.
Ok - what is the ad-hoc.sh, we execute in the dir and subdirs? It's another find:
-maxdepth 1 prevents find to search subdirs, -type says to just operate on files. -exec launches a command, for testing "echo zip ...", but if it looks promising (you do backups often, don't you?), you - well, here starts my pseudo code: -o:= -output "$PWD.zip", and {} + is the file list.
Every file with extension is a regular file, and every file without is a directory or a symlink to a dir (up3).
The {} has to be the last element of a find -exec command before the terminating ";" or +, so you have to build your 7z-command accordingly.
so if your 7za command is
the ad-hoc.sh might look like this: