Search code examples
regexbashunzip

Bash script to unzip a zip file then cd into it


I am trying to create a script that would CD into the file after i run unzip. I've done this for .tar files already but having trouble coming up with the regular expression for the zip. This is the command i run to unzip with force overwrite.

unzip -o my_file.zip

Archive:  my_file.zip
inflating: my_file/load.file
inflating: my_file/eccn.txt
inflating: my_file/my_file.tgz

Here is what i have tried using sed

unzip -o my_file.zip | sed "s|/.*$||"
Archive:  my_file.zip
  inflating: my_file
  inflating: my_file
  inflating: my_file

Here is how i handle .tar files:

tar -xvzf $fname                                        #tar it
topDir=$(tar -xvzf $fname | sed "s|/.*$||" | uniq)      #tars it verbosely and pipes it to uniq
[ $(wc -w <<< $topDir) == 1 ] || exit 1                 #check to see there is one entry in $topDir
cd $topDir                                              #cd into $topDir
echo your current dir is $PWD

tar -xvzf my_file.tgz | sed "s|/.*$||"
my_file
my_file
my_file
my_file
my_file

My question is how do i get rid of everything before my_file (e.g infalting: ) and then so i can cd into the extracted file?


Solution

  • If all you want to do is unzip a file an then cd into a folder, do just that:

    unzip my_file.zip; cd my_file
    

    It's also worth noting that zip files may contain more than one file or directory at the root level. So in the general case, there isn't exactly one directory to cd into. In fact, there could be none at all and it would still be a perfectly valid zip file.

    If you're certain that every zip file you're working with has exactly 1 directory, and you want to discover the name of that directory dynamically in code, the following command should get you that directory into a variable so you can cd into it:

    DIR=$(zipinfo -1 my_file.zip | grep -oE '^[^/]+' | uniq)
    unzip my_file.zip
    cd $DIR