1

I have a folder with 28 gz files with the extension .gz and 28 files with the extension .gz.bam.

I would like to unzip all the 28 .gz files and send them to another folder. I was doing one by one as follows:

gunzip -c file1.gz > /mnt/s3/data_transfer/file1

How can I specify I want the .gz and not the .gz.bam?

2 Answers2

1

With bash:

(
  ret=0
  shopt -s nullglob

  for file in *.gz; do
    gunzip < "$file" > /mnt/s3/data_transfer/"${file%.gz}" || ret="$?"
  done
  exit "$ret"
)

(also set the dotglob option if you also want to process the hidden .gz files, those whose name starts with a .).

In zsh:

(
  ret=0
  for file (*.gz(N.)) gunzip < $file > /mnt/s3/data_transfer/$file:r || ret=$?
  exit $ret
)

(also adding the . glob qualifier to restrict the glob expansion to regular files; add the D qualifier to process hidden files).

Stéphane Chazelas
  • 522,931
  • 91
  • 1,010
  • 1,501
1

Just iterate over them:

for file in *gz; do
    gunzip -c -- "$file"  > /mnt/s3/data_transfer/"${file%.gz}"
done

The "${file%.gz}" is shell syntax that will return the value of $file with the final .gz removed.

Note that this quick-n-dirty approach is less robust than Stéphane's below, and if you run it in a directory with no gz files, it will try to gunzip the *gz pattern itself. This won't be a problem as long as you do actually have file names ending in gz. Also, unlike his, this one will not exit with a fail status if one of the files fails to be decompressed correctly. If these are problems for you, please use his approach instead.

terdon
  • 234,489
  • 66
  • 447
  • 667
  • By using redirections instead of passing the file name as argument to `gzip`, you also avoid creating the destination file if the source file can't be opened. – Stéphane Chazelas Oct 11 '22 at 10:38
  • @StéphaneChazelas true, sorry, I clarified the exit status. And you're right about the redirection. I still feel a simple approach is worth mentioning since in most cases these things work perfectly well. – terdon Oct 11 '22 at 10:39