2

As the title suggests I need to .zip multiple files (thousands) in a folder and have each file zipped into their own archive with the original file name as the .zip filename.

If I try to do this with gzip, it is simple:

   $gzip *.fileextension

and it will .gz each file, delete the original and rename itself to the original filename

Example Input: file1.txt file2.txt file3.txt

Output: file1.gz file2.gz file3.gz

HOW DO I DO THIS WITH .ZIP?

2 Answers2

4

You can create a small bash shellscript zipsep,

#!/bin/bash

for i in "$@" do zip "$i".zip "$i" done

Make it executable,

chmod +x zipsep

Move it to a directory in PATH,

sudo mv zipsep /usr/local/bin

Now you can use zipsep to zip each file separately, for example

zipsep *.txt

If you want to remove the original files, you can do that separately afterwards in the example above by

rm *.txt

or interactively if only a few files (safer)

rm -i *.txt

It is also possible to put the removal into the shellscript, but I would prefer to do it separately.


Edit: If there will be no problem with files with the same name with different extensions for example file1.txt and file1.doc and file2.pdf, you can use a bash parameter substitution to remove the original extension from the zip file name. See man bash and search for 'Parameter Expansion' and ${parameter%word} 'Remove matching suffix pattern'.

#!/bin/bash

for i in "$@" do zip "${i%.*}".zip "$i" done

If you already created zip files without removing the original extension, you can use the following command to check, that it works as intended 'dry run',

rename -n 's/\.[a-zA-Z0-9]*\././' *.zip

and then remove the option -n to do it,

rename 's/\.[a-zA-Z0-9]*\././' *.zip

With this method you will avoid overwriting if there were original files with the same name and different extensions. At least my version of rename will refuse to overwrite, 'perl rename': See man rename:

The original "rename" did not check for the existence of target filenames, so had to be used with care. I hope I've fixed that (Robin Barker).

sudodus
  • 47,684
0

I ran a one liner "for loop" and got the desired output as you are asking for it.

for file in *;
do
  zip $file.zip $file
  rm -rf $file
done
  • what this is doing creating zip file with original file name and once the zip is created, it is removing the file.