(UnDe)压缩bash中的一个字符串?

问题描述 投票:9回答:2

是否可以在bash中使用stdinstdout压缩解压一个字符串?

我试过,但显然不支持。

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

我对linux不是很熟悉,但我读了其他压缩工具的手册,却找不到解决办法。

linux bash compression gzip
2个回答
7
投票

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.


13
投票

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.

© www.soinside.com 2019 - 2024. All rights reserved.