7

I know this can be done for single files, e.g.

gunzip -c my.gz > somedir/my

Can it be done for multiple files?

[UPDATE] I have a directory with a large number of .gz files (not .tar.gz), and I want to gunzip them into another directory while leaving the original files untouched.

6 Answers 6

9

try something like

for a in *.gz; do gunzip -c $a > somedir/`echo $a | sed s/.gz//`; done
6
  • Deleted my post.. Your one-liner is more simple :) Sep 29, 2010 at 20:25
  • basename might be a little simpler: for a in *.gz; do zcat $a > somedir/basename $a; done
    – Neil
    Sep 29, 2010 at 20:30
  • Thanks Neil, but basename $a doesn't work for me in bash on Mac as it appears above - perhaps some punctuation is missing?
    – Bio_X2Y
    Sep 29, 2010 at 20:49
  • Thanks Andrejs, Nifle, Neil. This command does the trick.
    – Bio_X2Y
    Sep 29, 2010 at 21:08
  • basename $a needed telling to remove the .gz. therefore: basename $a .gz Jul 30, 2011 at 11:54
2

This will work in bash

for FILE in *.gz
do
    echo -n "File $FILE... "
    gzip -c $FILE > ${FILE%.gz}
    echo "Done"
done

Building on Andreja's answer, adding correction for file names.

5
  • Forgot to add semicolons ;) Sep 29, 2010 at 20:28
  • Sorry, where exactly do they go? :)
    – Bio_X2Y
    Sep 29, 2010 at 20:35
  • Uhmm.. after each command within a loop? :) echo; gzip; echo; done... Sep 29, 2010 at 20:50
  • Ah yes, I missed the one before the first "do"! This works for me if I update to use gunzip and insert the target directory. More work needed to strip the ".gz" from the target uncompressed files. Thanks.
    – Bio_X2Y
    Sep 29, 2010 at 20:57
  • This extracts my text files from .gz files all garbled.
    – Andy N
    Apr 19, 2013 at 16:52
2

Assuming that each file has a name like

foo.bar.gz

basename (GNU coreutils 8.4) can give you the original uncompressed file's name, thus I'd do

for f in /source/dir/*.gz; do t=$(basename $f .gz); gunzip -c $f > /target/dir/$t; done
2

This also works. Just another way of doing it. It will not garble up your extracted text files. I have actually tested this.

for f in *.gz; do
  STEM=$(basename "${f}" .gz)
  gunzip -c "${f}" > /somedir/"${STEM}";
done
0

Sounds like job for a quick perl/python/ruby/etc. script.

Just adjust the code in this example to apply the necessary gunzip command.

0

This version preserves the original filetimes as inplace gzip does, and is "space-safe":

IFS=$'\n';for a in *.gz; do d=`basename $a .gz`;echo gunzip -c $a > somedir/$d; touch somedir/$d -r $a; done;

I found quoting "$a" and "$d" thus, was unnecessary as bash appeared to automatically escape spaces.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .