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

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

2
  • Thank you very much, it works ! I was looking for this solution exactly. 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
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.

0

This zips files in the current directory to separate archives and removes the extension.

#!/bin/bash
it=0; for f in *.*; do fn=$(echo "${f%%.*}"); filearray[${it}]="${fn}"; ((it=it+1)); done; total=it; for it in "${filearray[@]}"; do zip "$it.zip" "$it".*; done

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.