Linux (Un/De) 在 bash 中压缩一个字符串?

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

(Un/De)compress a string in bash?

linuxbashcompressiongzip

提问by Jane Watson

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

是否可以使用 stdin/stdout 在 bash 中压缩/解压缩字符串?

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?

我不精通 linux,但我阅读了其他压缩实用程序手册页,但找不到解决方案?

采纳答案by Micha? ?rajer

When you do:

当你这样做时:

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

You don't have same same bytes in variable heyas you have in /tmp/myfilecreated by:

您在变量hey中没有与在/tmp/myfile创建时相同的字节:

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.

您收到“gzip: stdin is a multi-part gzip file -- not supported”错误,仅仅是因为您破坏了无法解压缩的压缩数据。

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

VAR=$(...)结构是为处理文本而设计的。例如,这就是为什么您会获得额外的尾随修剪。

回答by Micha? ?rajer

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

如果您可以接受 33% 的压缩率损失,那么您可以存储 base64 编码的压缩数据:

me$mybox$ FOO=$(echo "Hello world" | gzip | base64) # 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.

它会工作,但每 3 个(压缩)字节将存储在 4 个字节的文本中。