How to archive each file in a folder separately?

388 Views Asked by At

I have many files in a folder. If I have a single file, 7z a -t7z archive1.zip -mx0 works fine. But my files are file1, file2 ... I want to archive these files separately like archive1.zip, archive2.zip ...

Note: File names are random and archive names don't necessarily be regular like archive2, archive3. All I want archive names must be parallel to file names. For example screenshot.jpg > screenshot.zip, book.pdf > book.zip

1

There are 1 best solutions below

3
On

I think a good way to do this is using find :

find . -maxdepth 1 -type f -not -name "*.zip" -exec sh -c '7z a -t7z "${1%.*}.zip" -mx0 {}' sh {} \;

-maxdepth 1 is used to not enter subdirectories
-not -name "*.zip" is used to exclude archives
-exec sh -c '' sh {} is there just to be able to strip the extension from the filename
"${1%.*}.zip" transforms filename.extension into filename.zip