Super User is a question and answer site for computer enthusiasts and power users. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I have directory containing big list of files. I'd like to gzip each file of a certain mask to a separate archive. How do i do that automatically?

For example here's sample directory contents: - index.html - start.html - myfile1.txt - myfile2.txt - myfile3.txt

How to i create separate archive (myfile1.tar.gz,myfile2.tar.gz ...) for each file starting with 'myfile*' ?

share|improve this question
up vote 0 down vote accepted

if you use the bash it could look like this

for file in `ls abc_*`; do tar -czvf $file.tar.gz $file ; done

you simply change the "abc_" to your beginning filename.

Be careful it will re compress the already compressed files, because they start like the normal files.

Best regards Kenny

share|improve this answer
    
Thank you very much, it works ! I was looking for this solution exactly. – user1184899 Feb 16 '12 at 15:19
    
This breaks on files with spaces in their name. And why not use for file in abc_* instead of for file in $(ls abc_*)? – slhck May 30 '12 at 6:21

I assume you are working on a linux box with GNU coreutils. In bash do something like

find -name "myfile*" -print0 | xargs -n 1 -0 gzip

To understand the above command line, look up the options in man find and man xargs. No need to tar single files, I think. If, for some mysterious reason, you really need it in the way you wrote above, use something like

find -name "myfile*" -print0 | \
while IFS="" read -r -d $'\0' file
do 
  [ -f "${file%.*}.tar.gz" ] || tar czvf "${file%.*}.tar.gz" "${file}"
done

Look up the explanations in man bash. Cheers!

PS: To filter out already compressed files use a [ "${file##*.}" == "gz" ] || precondition before the overwrite protection.

share|improve this answer

You must log in to answer this question.

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