I have an addition to @Alex Stragies conversion for those who need a proper header and footer (an actual conversion from zlib to gzip).
It would probably be easier to use one of the above methods, however if the reader has a case like mine which requires conversion of zlib to gzip without decompression and recompression, this is the way to do it.
According to RFC1950/1952, A zlib file can only have a single stream or member. This is different from gzip in that:
A gzip file consists of a series of "members" (compressed data
sets). ... The members simply appear one after another in the file,
with no additional information before, between, or after them.
This means that while a single zlib file can always be converted to a single gzip file, the converse is not strictly true. Something to keep in mind.
zlib has both a header (2 bytes) and a footer (4 bytes) which must be removed from the data so that the gzip header and footer can be appended. One way of doing that is as follows:
# Remove zlib 4 byte footer
trunc_size=$(ls -l infile.z | awk '{print $5 - 4}')
truncate -s $trunc_size infile.z
Remove zlib 2 byte header
dd bs=1M iflag=skip_bytes skip=2 if=infile.z of=tmp1.z
Now we have just raw data and may append the gzip header (from @Alex Stragies)
printf "\x1f\x8b\x08\x00\x00\x00\x00\x00\x00\x00" | cat - tmp1.z > tmp2.z
The gzip footer is 8 bytes long. It consists the CRC32 of the uncompressed file, plus the size of the file uncompressed mod 2^32, both in big endian format. If you don't know these but have means of getting an uncompressed file:
generate_crcbig() {
crc=$(crc32 $uncompressedfile)
crcbig=$(echo "\x${crc:6:2}\x${crc:4:2}\x${crc:2:2}\x${crc:0:2}")
}
generate_lbig () {
leng=$(ls -l $uncompressedfile | awk '{print $5}')
lmod=$(expr $leng % 4294967296) # mod 2^32
lhex=$(printf "%x\n" $lmod)
lbig=$(echo "\x${lhex:6:2}\x${lhex:4:2}\x${lhex:2:2}\x${lhex:0:2}")
}
And then the footer may be appended as such:
printf $crcbig$lbig | cat tmp3.z - > outfile.gz
Now you have a file which is in the gzip format! It can be verified with gzip -t outfile.gz
and uncompressed with any application complying with gzip specifications.