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
Putting 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
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
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