Home > Software design >  Need to zip individual files of certain size & remove the original files in unix
Need to zip individual files of certain size & remove the original files in unix

Time:05-16

I want to zip individual files gotten from an output & delete the original files. The objective is to find files greater than 9MB and zip each file of that size individually & remove its original instance. Something like this..

find test* -type f - size  9M 
zip -m <filenames (from the above output)> <individual filename.zip>

expected output -

test_abc1.txt.1.zip
test_abc2.txt.2.zip
test_abc3.txt.zip

CodePudding user response:

For zipping individual files with find, the main problem is how to generate the zip filenames automatically; for that you can use shell parameter expansions in a find -exec inline script:

find test* -type f -size  9M -exec sh -c '
    for f
    do
        z=${f##*/}.zip
        zip -j -m "$z" "$f"
    done
' _ {}  
notes:
  • The z=${f##*/}.zip strips the directory path component of $f and append a .zip at the end; for example, if $f is test1/file.txt, then $z will be file.txt.zip.
    If you also want to replace the file extension by .zip then you can use z=${f##*/} z=${z%.*}.zip instead.

  • The -j option of zip is for stripping the directory path inside the ZIP archive.

  • The -m option of zip is for removing the input file(s) after successful generation of the ZIP archive.

  • Related