How to ZIP files recursively in Emacs

931 Views Asked by At

How can I zip files in Dired, where trying to add a folder to the zip, it will also add the files in that folder recursively?

2

There are 2 best solutions below

2
On

You can (un)compress individual files using Z which runs the command dired-do-compress.

You can also do something like this:

(defun sds-dired-zip-file ()
  "ZIP the current file and all subdir's; or unZIP if already a ZIP."
  (interactive)
  (let* ((fn (dired-get-filename)) (nd (file-name-nondirectory fn)) cmd msg)
    (cond ((and (string-match ".zip$" fn)
                (y-or-n-p (format "unzip %s? " fn)))
           (setq msg "unZIPing file %s..." cmd (concat "unzip " nd)))
          ((and (or (string-match ".tgz$" fn) (string-match ".tar.gz$" fn))
                (y-or-n-p (format "tar xfz `%s'? " fn)))
           (setq msg "unTAR/GZIPing file %s..." cmd (concat "tar xfz " nd)))
          ((and (or (string-match ".tbz2$" fn) (string-match ".tar.bz2$" fn))
                (y-or-n-p (format "tar xfj `%s'? " fn)))
           (setq msg "unTAR/BZIPing file %s..." cmd (concat "tar xfj " nd)))
          ((and (string-match ".tar$" fn)
                (y-or-n-p (format "tar xf `%s'? " fn)))
           (setq msg "unTARing file %s..." cmd (concat "tar xf " nd)))
          ((and (string-match ".rar$" fn)
                (y-or-n-p (format "unrar x `%s'? " fn)))
           (setq msg "unRARing file %s..." cmd (concat "unrar x " nd)))
          ((and (file-directory-p fn)
                (y-or-n-p (format "zip -rmv9 `%s'? " fn)))
           (setq msg "ZIPing directory %s..."
                 cmd (concat "zip -rmv9 " nd ".zip " nd)))
          ((y-or-n-p "(un?)compress? ") (dired-do-compress)))
    (when cmd
      (message msg fn)
      (shell-command (concat "cd " (file-name-directory fn) " && " cmd))
      (revert-buffer))))
(define-key dired-mode-map "I" 'sds-dired-zip-file)
0
On

Mark the files with m, then press ! and type zip -r yourfile.zip *.