Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

(Un/De)compress a string in bash?

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?

like image 506
Jane Watson Avatar asked Sep 24 '11 11:09

Jane Watson


1 Answers

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.

like image 88
Michał Šrajer Avatar answered Sep 21 '22 11:09

Michał Šrajer