Gzip multiple files individually and keep the original files

北城余情 提交于 2019-12-20 10:37:02

问题


I am looking to gzip multiple files (into multiple .gz files) in a directory while keeping the originals.

I can do individual files using these commands:

find . -type f -name "*cache.html" -exec gzip {} \;

or

gzip *cache.html

but neither preserves the original. I tried

 find . -type f -name "*cache.html" -exec gzip -c {} > {}.gz

but that only made a {}.gz file. Is there a simple way to do this?


回答1:


Your > in the last command gets parsed by the same shell which runs find. Use a nested shell:

find . -type f -name "*cache.html" -exec sh -c "gzip < {} > {}.gz" \;



回答2:


I'd use bash(1)'s simple for construct for this:

for f in *cache.html ; do gzip -c "$f" > "$f.gz" ; done

If I knew the filenames were 'sane', I'd leave off the "" around the arguments, because I'm lazy. And my filenames are usually sane. But scripts don't have that luxury.




回答3:


-k, --keep

gzip 1.6 (June 2013) added the -k, --keep option, so now you can:

find . -type f -name "*cache.html" -exec gzip -k {} \;
gzip -k *cache.html

or for all files recursively simply:

gzip -kr .

Found at: https://unix.stackexchange.com/questions/46786/how-to-tell-gzip-to-keep-original-file




回答4:


Since you have multiple files, GNU Parallel might be useful:

find . -type f -name "*cache.html" | parallel gzip '<{} >{}.gz'

Watch the intro video for a quick introduction: https://www.youtube.com/playlist?list=PL284C9FF2488BC6D1



来源:https://stackoverflow.com/questions/6258972/gzip-multiple-files-individually-and-keep-the-original-files

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!