0

I have the current code:

for fname in *.*; do
    prefix=${fname%.*}
    [ ! -f "$fname" ] || [ -f "$prefix.zip" ] && continue
    zip "$prefix" "$prefix".*
done

This mostly does what I want, but I have to delete the original files. Is there a modification that can be made to remove the original files after compression? If possible, how can I execute this on a directory or its subdirectories?

The current file structure is as follows:

-rootDir
|- Dir1
 |- file1.jpg
 |- file1.png
 |- file1.mp3
|- Dir2
 |- file2.jpg
 |- file2.png
 |- file2.mp3

I am aiming for the structure below:

-rootDir
|- Dir1
 |- file1.zip
|- Dir2
 |- file2.zip

As mentioned, the above code works fine when executed in a single directory.

I now have 300 subdirectories, and it would be of great assistance to me if I could obtain a modified version of the above code to execute at the root directory level, as well as tidy up the remaining files.

1 Answer 1

0

zip has a --move (-m) option to ask it to move files into an archive, i.e. delete them after they’ve been successfully added to the archive. It is recommended to pair it with the -T option to test the archive before actually removing the files:

zip -mT "$prefix" "$prefix".*

To handle multiple directories, you can loop over them:

for dir in */; do
    (cd "$dir" && for fname in *.*; do
        prefix="${fname%.*}"
        [ ! -f "$fname" ] || [ -f "$prefix.zip" ] && continue
        zip -mT "$prefix" "$prefix".*
    done)
done
0

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .