Creating separate archives for a set of files

1

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*' ?

user1184899

Posted 2012-02-16T10:57:26.520

Reputation: 113

Answers

1

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

phschoen

Posted 2012-02-16T10:57:26.520

Reputation: 251

Thank you very much, it works ! I was looking for this solution exactly. – user1184899 – 2012-02-16T15:19:49.133

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 – 2012-05-30T06:21:25.873

1

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.

Speckinius Flecksis

Posted 2012-02-16T10:57:26.520

Reputation: 313