Extract only a specific file from a zipped archive to a given directory

  • I need to extract a single file from a ZIP file which I know the path to. Is there a command like the following:

    unzip -d . myarchive.zip path/to/zipped/file.txt
    

    Unfortunately, the above command extracts and recreates the entire path to the file at ./path/to/zipped/file.txt. Is there a way for me to simply pull the file out into a specified directory?

  • You can extract just the text to standard output with the -p option:

    unzip -p myarchive.zip path/to/zipped/file.txt >file.txt
    

    This won't extract the metadata (date, permissions, …), only the file contents. That's the price to pay for the convenience of not having to move the file afterwards.

    Alternatively, mount the archive as a directory and just copy the file. With AVFS:

    mountavfs
    cp -p ~/.avfs"$PWD/myarchive.zip#"/path/to/zipped/file.txt .
    

    Or with fuse-zip:

    mkdir myarchive.d
    fuse-zip myarchive.zip myarchive.d
    cp -p myarchive.d/path/to/zipped/file.txt .
    fusermount -u myarchive.d; rmdir myarchive.d
    

    Will it work for binary files, say a `jar` file?

    @TKKocheran: Jar files are zips, so the unzip and fuse-zip methods will obviously work. The AVFS method also works, because AVFS guesses the format based on file names and knows about `.jar`; if your file is named differently you might need to tell AVFS to use its zip handler, e.g. `~/.avfs$PWD/foo.apk#uzip/META-INF`.

    actually, I meant extracting a JAR/binary file from a ZIP archive. I haven't had the chance to test it out yet, can you see any issues using the first command above to extract binary files?

    @TKKocheran: There's no problem, `-p` extracts the file as-is (`-c` does text conversion).

    I think the answer of @Myles is more elegant, because it doesn't require output redirection and it preserves file attributes.

License under CC-BY-SA with attribution


Content dated before 6/26/2020 9:53 AM