hobbyking
hobbyking

Reputation: 97

How to create individual zip file for each of .py file

I need to create a bash script that create individual zip file for each of python file in the same directory.

I found the following command could create the zip with the file and original file extension. e.g created test.py.zip for test.py

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

How can I update the command to get rid of the original file extension. e.g. test.zip instead of test.py.zip

Thanks in advance.

Upvotes: 0

Views: 338

Answers (2)

donkopotamus
donkopotamus

Reputation: 23176

You can strip an extension using basename <file> <extension>. There are a variety of ways you could arrange to do that.

Using a loop in bash

For example, loop through the results from find and then zip the file:

for f in $(find . -name '*.py')
do 
    zip "$(basename "$f" .py).zip" "$f"
done

Using a subshell in find

Unfortunately we can't use $(...) in find ... -exec directly. However we can always invoke a shell and do it there:

find . -name '*.py' -exec sh -c 'zip "$(basename "$0" .py)".zip "$0"' '{}' \;

Upvotes: 2

blhsing
blhsing

Reputation: 106435

You can't do that with find's -exec option. You can use bash's while loop and sed to process find's output instead:

find . -name '*.py' -print | while read FILE; do zip `echo $FILE|sed 's/\py$//'`zip $FILE; done

Upvotes: 1

Related Questions