How to recompress gzipped .gz files to .xz files on Linux

Copy and paste this shell function into your bash or zsh:

function gzToXz { zcat "$1" | xz -c - -ev9 > "${1%.*}.xz" ; }

This will decompress the file using zcat and pipe it into xz with the highest compression setting (-ev9). If you prefer less compression but more speed, use e.g. -5 instead of -ev9.

Use like this:

gzToXz my.gz

which will recompress my.gz to my.xz.

In case you want to recompress every .gz file in the current directory, use:

for i in *.gz ; do echo "$i" ; gzToXz "$i" ; done

It might be best to make a backup of the data even though I have used this script many times for my own data.