I have a zip file with always the same name : toto.zip Inside there is only 1 file with the name who can change based on a version: totoInstaller-20210321_titi.pkg

I would like to extract the name of the extracted file from a shell script (I'm on macOS) and store it on a variable to use it later ... All I'm trying is not working... any help appreciated.

3 Answers 3

filename=$(unzip toto.zip | awk 'sub(/^[[:space:]]*inflating:[[:space:]]+/,""){print; exit}')

should work robustly and efficiently using any awk (but is untested). Also consider doing similar with the output of unzip -l.


This should work (although sometimes, there are differences between versions of sed and unzip available from one system to another):

filename=$(unzip toto.zip | sed -n 's/^[[:space:]]*inflating:[[:space:]]*//p')

This command unzips the file and send the output to sed. sed looks for lines starting with whitespace and then inflating: . If such a line is found, sed will delete everthing up to and including the inflating: and any subsequent whitespace and then it will print what is left, which should be the file name. Everything else is discarded (thanks to option -n). Finally, we store the output in variable filename.

  • 2
    I don't think that sed will work on macOS. Try this one instead: sed -n '/inflating: /s/[[:space:]]*inflating:[[:space:]]*\(.*\)$/\1/p.
    – terdon
    Mar 22, 2021 at 19:02
  • 1
    But there is no need to match twice or to include the rest of the line. It should be enough to do sed -n 's/^[[:space:]]*inflating:[[:space:]]*//p'
    – terdon
    Mar 22, 2021 at 19:04
  • @terdon Hmm, I should stop answering questions for other OSes involving sed... I initially captured the filename in a group because of possible trailing whitespaces but finally decided against it.
    – lgeorget
    Mar 23, 2021 at 9:40

Thanks, both sed & awk worked even if they both let an extra space at the end to trim

Why using unzip -l here?

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .