bash 如何压缩多个文件夹,每个文件夹都有自己的 zip 存档?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20452384/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to compress multiple folders, each into its own zip archive?
提问by Villi Magg
So I want to create a script that enables me to compresses each folder into its own zip archive and not into a one big zip file.
所以我想创建一个脚本,使我能够将每个文件夹压缩到它自己的 zip 存档中,而不是压缩到一个大的 zip 文件中。
As an example, I've got a directory:
例如,我有一个目录:
+ MyDirectory/
| |
| + Folder_01/
| |
| + Folder_02/
| |
| + Folder_03/
|
When I'm done running the script under MyDirectory
then I would have a zip file of each Folder which is inside MyDirectory
: Folder_01.zip
, Folder_02.zip
and Folder_03.zip
.
I know some BASH but this is something I can't figure out.
当我做下运行的脚本,MyDirectory
然后我会每个文件夹的zip文件是内部MyDirectory
:Folder_01.zip
,Folder_02.zip
和Folder_03.zip
。我知道一些 BASH,但这是我无法弄清楚的。
How can this be done?
如何才能做到这一点?
Kind regards.
亲切的问候。
回答by Igor Chubin
for i in *
do
[ -d "$i" ] && zip -r "$i.zip" "$i"
done
You walk through all the directories and create zip for each of them.
您遍历所有目录并为每个目录创建 zip。
Or even more concise:
或者更简洁:
for i in */; do zip -r "${i%/}.zip" "$i"; done
(thanks to damienfrancois for suggestion).
(感谢 damienfrancois 的建议)。
回答by ahmed zeaad
here
这里
for i in */; do tar -czvf "${i%/}.tar.gz" "$i"; done
回答by Gajus
Consider using xz
algorithm if you require smaller output (at the cost of longer process):
xz
如果您需要较小的输出(以较长的过程为代价),请考虑使用算法:
for d in */ ; do
outName=$d;
outName=${outName// /\-};
outName=${outName//[!0-9a-z-]};
dirName=$d;
dirName=${dirName//\/}
tar -c "$dirName" | xz -e > $outName.tar.xz
done
This code will sanitise folder names and produce .tar.xz
for every folder in the current directory.
此代码将清理文件夹名称并.tar.xz
为当前目录中的每个文件夹生成。