Let have a directory with lots of individual .txt files. My purpose is to find the individual files in the directory, zip them with the same name (excluding .txt) individually and remove the original file.

It is very easy to use gzip like below:

find .* -type f | xargs gzip 

but I need to zip the files instead.

NOTE: I do not have sudo privilege

  • Is the 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?` Jul 5, 2019 at 10:46
  • How about 'zip -m <pattern>.txt' ?
    – gerhard d.
    Jul 5, 2019 at 10:47
  • 1
    @msp9011 yes only the current directory
    – TPArrow
    Jul 5, 2019 at 10:49
  • @NasirRiley yes it is installed. Only current directory. Yes there are a mixture of files in the directory
    – TPArrow
    Jul 5, 2019 at 10:50

2 Answers 2


From man:

          Move  the  specified  files  into the zip archive; actually, this deletes the target directories/files after making the specified zip archive. If a directory
          becomes empty after removal of the files, the directory is also removed. No deletions are done until zip has created the archive without error.  This is use-
          ful  for  conserving  disk  space, but is potentially dangerous so it is recommended to use it in combination with -T to test the archive before removing all
          input files.

To compress ann files in current direstory

zip -m test.zip *.txt

Try this,

for i in *.txt; 
  zip -m "${i%.*}.zip" "${i%.*}".*; 

The above code will take all file with .txt as extension in a for loop and zip each file with their prefix name...



$ ls -1

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 {} \;


$ ls -1

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"' _ {} \;


$ ls -1

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.