catteneo
catteneo

Reputation: 175

Script to create individual zip files for each .txt file it finds and move them after

I need a shell script that basically does this:

Basically its a script to substitute a list of txt files for its zip equivalent but keeping the same name.

I've have used find to find the files that I want to zip:

find . -name '.txt.' -print

The Results are:

./InstructionManager.txt.0
./InstructionManager.txt.1

Those are the files I want to zip individually (of course they will be a lot more), but don't know how to use them as arguments individually for make commans like:

zip ./InstructionManager.txt.0.zip ./InstructionManager.txt.0
mv ./InstructionManager.txt.0.zip ./InstructionManager.txt.0
zip ./InstructionManager.txt.1.zip ./InstructionManager.txt.1
mv ./InstructionManager.txt.1.zip ./InstructionManager.txt.1

Any Ideas? And no, i don't want a zip with all the files :S Thanks

Upvotes: 17

Views: 23564

Answers (4)

Jamie
Jamie

Reputation: 11

If you want to delete the original file after zipping everything individually then you can use the following command.

$ find . -name '*.txt.*' -print -exec zip '{}'.zip '{}' \; -exec rm '{}' \;

Upvotes: 1

Stephane Rouberol
Stephane Rouberol

Reputation: 4384

With find and xargs, file names with spaces accepted:

find . -name '*.txt.*' -print0 | xargs -0 -r -n1 -I % sh -c '{ zip %.zip %; mv %.zip %;}'

files are zipped, then renamed to their original name

Upvotes: 1

Sicco
Sicco

Reputation: 6271

find . -name '*.txt.*' -print -exec zip '{}'.zip '{}' \; -exec mv '{}'.zip '{}' \;
  • Find the .txt files
  • The first -exec zips the files
  • The second -exec renames the zipped files to the original names

Note that this procedure overwrites the original files. To be sure that the new files are actual zip files, you can do:

file InstructionManager.txt.*

Which should return:

InstructionManager.txt.0: Zip archive data, at least v1.0 to extract
InstructionManager.txt.1: Zip archive data, at least v1.0 to extract

Upvotes: 31

perreal
perreal

Reputation: 97948

Using find and zip:

find . -name '*.txt.*' -exec zip '{}.zip' '{}' \;

Upvotes: 14

Related Questions