I'm looking for a terminal command to count the number of top-level items in a ZIP archive. I know that zip -l archive.zip will show the file count, but this shows all files, not just top-level items. If archive.zip will unzip to the following (* indicates top-level)

* Dir1
* Dir2
* Dir3
* File7
* File8

then I would like a program to output 5.

  • Use unzip -l archive.zip|grep /|grep -v "/.*/"|wc -l. The first filter shows only the lines with files, the second eliminates subdirectories and the third returns the line count. If the archive has absolute paths, you'll need to allow two slashes and eliminate three or more. – AFH Mar 14 '17 at 16:25
  • This shows the number of non-top level items. But I guess I can just subtract from the output of unzip -l archive.zip | grep -v / | wc -l, right? Sorry that my original post wasn't clear – BallpointBen Mar 14 '17 at 16:50
  • If you miss off the |wc -l you'll see the files considered, and it's the top-level ones. There is a bug(!): if the archive path contains a single / this will be counted, so you need an extra filter to exclude it, eg replace grep / by grep "^ .*/". – AFH Mar 14 '17 at 17:09

Took inspiration from AFH to use this solution

zipinfo -1 archive.zip | 
    egrep '^[^/]+/?$' | 
    egrep -v '__MACOSX' | 
    wc -l |
    awk '{$1=$1};1'

What it does:

Get list of files in archive
Filter for top-level files or dirs; must either contain no '/' or end in '/'
Remove lines containing __MACOSX (for archives created on a Mac)
Get line count
Remove trailing whitespace; http://unix.stackexchange.com/a/205854/169465

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.