Find out the name of a folder in a root directory inside .zip file

5,579

Solution 1

This command seems to do what you want:

unzip -qql myzip.zip | head -n1 | tr -s ' ' | cut -d' ' -f5-

Or with GNU sed:

unzip -qql myzip.zip | sed -r '1 {s/([ ]+[^ ]+){3}\s+//;q}'

Solution 2

unzip -Z invokes Zipinfo mode, which means you could call unzip -Z -1 myzip.zip | head -1 for the same result, but it's a lot more terse

Solution 3

You can do it with the following shell command:

unzip -qql myzip.zip | head -n1 | awk '{print $4}'

It is a unix command pipeline. unzip -qql lists the files in the zip file. head -n1 cuts its first line, while awk '{print $4}' prints its fourth word.

Note, it doesn't work correctly it the first entry in the zip file contains a space. Typically, it is a bad practice to process the output of such commands, but it might be okay for a quick & dirty solution.

Share:
5,579
Jan Hrcek
Author by

Jan Hrcek

I work as senior quality engineer at Red Hat. I'm responsible for quality of web tooling for Drools and jBPM projects. In my free time I love studying mathematics and playing with functional programming languages like Haskell and Elm.

Updated on September 18, 2022

Comments

  • Jan Hrcek
    Jan Hrcek over 1 year

    I'm using Fedora 17 and bash as my shell. I have a specific zip file, which has just one folder in it's root. I.e. upon unpacking the zip file i see the following:

    > unzip myzip.zip
    > ls
    myzip.zip folderThatWasInsideZip

    Supposing you know, that there is only 1 folder packed in the zip file, how do I find out the name of the main folder inside the zip file, without actually unpacking the zip file?

    I'm looking for a one-liner, that would enable me to do something like this:

    > <command> myzip.zip
    folderThatWasInsideZip

    I know there are ways to list all the files in the zip with less, but that lists all the files in the subdirectories etc. I just want to know the name of the one folder. I know I'm missing something basic..

    • l1zard
      l1zard over 11 years
      the -l option is used to list the files rather than unpack the zip file. see man unzip.
  • Thor
    Thor over 11 years
    @JanHrcek: looking at gdb traces for unzip and unzip -l shows that inflate_block() function is not called with -l, i.e. the file is not decompressed, only meta data is read.
  • Jan Hrcek
    Jan Hrcek over 11 years
    Yes, you're right :) Sorry.