Linux 如何gzip bash中所有子目录中的所有文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10363921/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 06:03:23  来源:igfitidea点击:

How to gzip all files in all sub-directories in bash

linuxbashshellloopsgzip

提问by Farshid

I want to iterate among sub directories of my current location and gzip each file seperately. For zipping files in a directory, I use

我想在我当前位置的子目录之间进行迭代,并分别对每个文件进行 gzip。为了压缩目录中的文件,我使用

for file in *; do gzip "$file"; done

but this can just work on current directory and not the sub directories of the current directory. How can I rewrite the above statements so that It also zips the files in all subdirectories?

但这只能在当前目录上工作,而不能在当前目录的子目录上工作。如何重写上述语句,以便它还压缩所有子目录中的文件?

采纳答案by Adam Liss

No need for loops or anything more than findand gzip:

不需要循环或除了findand之外的任何东西gzip

find . -type f ! -name '*.gz' -exec gzip "{}" \;

This finds all regular files in and below the current directory whose names don't end with the .gzextension (that is, all files that are not already compressed). It invokes gzipon each file individually.

这将查找当前目录中和其下名称不以.gz扩展名结尾的所有常规文件(即,所有尚未压缩的文件)。它gzip单独调用每个文件。



Edit, based on comment from user unknown:

编辑,基于评论user unknown

The curly braces ({}) are replaced with the filename, which is passed directly, as a single word, to the command following -execas you can see here:

大括号 ( {}) 替换为文件名,文件名作为单个单词直接传递给以下命令,如下所示-exec

$ touch foo
$ touch "bar baz"
$ touch xyzzy
$ find . -exec echo {} \;

./foo
./bar baz
./xyzzy

回答by Tim Pote

find . -type f | while read file; do gzip "$file"; done

回答by Supernormal

I'd prefer gzip -r ./which does the same thing but is shorter.

我更喜欢gzip -r ./哪个做同样的事情但更短。