Consider:
$ ls -1
a.txt
b.txt
c.txt
d.jpg
The following command will zip each .txt
file in the current directory and remove the original file:
find . -maxdepth 1 -type f -name '*.txt' -exec zip -Tm {}.zip {} \;
Result:
$ ls -1
a.txt.zip
b.txt.zip
c.txt.zip
d.jpg
Note: we used the -T
option to test the integrity of the archive before removing the input file. This is recommended in the zip
man page for the -m
option.
Note that the .txt
part is still present in the filename. This is how gzip
behaves as well.
To remove the .txt
part:
If you don't want the .txt
part to remain in the filename, the following command will achieve this:
find . -maxdepth 1 -type f -name '*.txt' -exec bash -c \
'zip -Tm "${1%.txt}".zip "$1"' _ {} \;
Result:
$ ls -1
a.zip
b.zip
c.zip
d.jpg
Note: we provided _
as the 0th argument to the shell script so that the positional arguments to our script start at 1 as usual. Any value could have been used. This is discussed in the BashFAQ.
zip
package installed on the system that you are using? Do you just want to operate on the files in the current directory or in the subdirectores (if they exist)? Are there files in that directory other than the ones ending in.txt
?`