(Un/De)compress a string in bash?

こ雲淡風輕ζ 提交于 2020-08-02 07:05:21

问题


Is it possible to compress/decompress a string in bash using stdin/stdout ?

I tried this but apparently it is not supported ?

hey=$(echo "hello world" | gzip -cf)
echo $hey # returns a compressed string
echo $hey | gzip -cfd
gzip: stdin is a multi-part gzip file -- not supported

I'm not well versed in linux but I read other compression utilities man pages and couldn't find a solution?


回答1:


When you do:

hey=$(echo "hello world" | gzip -cf)

You don't have same same bytes in variable hey as you have in /tmp/myfile created by:

echo "hello world" | gzip -cf > /tmp/myfile

You get "gzip: stdin is a multi-part gzip file -- not supported" error simply because you have broken compressed data which cannot be uncompressed.

The VAR=$(...) construction is designed for working with text. This is why you get extra trailing trim for example.




回答2:


If 33% compression rate loss is acceptable for you, then you can store base64 encoded compressed data:

me$mybox$ FOO=$(echo "Hello world" | gzip | base64 -w0) # compressed, base64 encoded data
me$mybox$ echo $FOO | base64 -d | gunzip # use base64 decoded, uncompressed data
Hello world

It will work, but each 3 (compressed) bytes will be stored in 4 bytes of text.



来源:https://stackoverflow.com/questions/7538846/un-decompress-a-string-in-bash

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