How do I compress every file in a directory into its own tar whilst preserving the name for each file?
i.e. file1.out file2.out
-->
file1.out.tar.gz file2.out.tar.gz
Server Fault is a question and answer site for system and network administrators. It only takes a minute to sign up.
Sign up to join this communityPutting every file into a separate tar file doesn't make any sense in this scenario. You can use gzip
to compress them directly:
gzip *
will result in file1.out.gz
, file2.out.gz
etc.
You would use tar
only if you would need a compressed archive as a single file.
If you ineed need a tar archive for every file, you can create it like so:
for i in *; do tar -czf $i.tar.gz $i; done
find . -maxdepth 1 -type d ! -path . | while read a_dir; do tar -zcvf ${a_dir}.tgz ${a_dir} --remove-files; done
find . -maxdepth 1 -mindepth 1 -type d -exec tar -zcvf {}.tgz {} --remove-files \;
To build on @SvenW's answer (which will only work on the current directory), if you have a HUGE number of files or want to do it on a recursive directory structure you can also use
find . -type f -exec gzip \{\} \;
and if you need to put the output into a different directory (in this example, ../target
) and don't want to remove the originals, you can do something like:
find . -type f -print | while read fname ; do
mkdir -p "../target/`dirname \"$fname\"`"
gzip -c "$fname" > "../target/$fname.gz"
done
find . -type f -exec gzip {} \;
will be sufficient. The second code will fail with filenames containing spaces and the like.
Feb 6, 2012 at 2:29
{}
as a force of habit). Others have already posted those as answers to your question, however.
find . -type f -exec grep -Iq . {} \; -and -exec gzip {} \;
Try this one:
#!/bin/bash
for fich in *; do
if [ "$fich" != "*" ] ; then
gzip -9 -c $fich > $fich.tar.gz
\mv $fich.tar.gz $fich
fi
done