Fun fact: If you use Archive Manager and extract a .tar.gz so that you have "Keep directory structure" unticked, you will get a tarbomb.

tar -ztf lists all the files and directories in a tar file. Is there a way to list all the files in a tar file, without the directory structure?

  • You can get the 'tarbomb' effect with tar xvzf my_tar.tar.gz --transform 's/.*\///'. But unfortunately that doesn't change how it displays in a listing with t rather than x. – ire_and_curses Nov 15 '13 at 15:37
  • 4
    What bothers me is that even well structured archives can so easily be used to create weapons of mass extraction. – Eero Aaltonen Nov 20 '13 at 12:46

I don't see a way to do it from the man page, but you can always filter the results. The following assumes no newlines in your file names:

tar tzf your_archive | awk -F/ '{ if($NF != "") print $NF }'

How it works

By setting the field separator to /, the last field awk knows about ($NF) is either the file name if it's processing a file name or empty if it's processing a directory name (tar adds a trailing slash to directory names). So, we're basically telling awk to print the last field if it's not empty.

  • Pretty nice work with awk :) – Eero Aaltonen Nov 15 '13 at 13:37

Assuming none of the file names contain newlines:

tar -tf foo.tar | sed -e 's#.*/##' -e '\#.#!d'

The first sed command removes everything before the last / on a line, so that only the file name part is printed. The second command deletes the lines which are now empty, i.e. the lines that ended in a /, which are directories.

  • sed: -e expression #2, char 2: unknown command: `/' and the sed syntax does not feel very.. intuitive – Eero Aaltonen Nov 20 '13 at 12:44
  • @EeroAaltonen I fixed the sed command. Indeed, the syntax is somewhat cryptic (I do include explanations in my answer). – Gilles Nov 20 '13 at 12:56

Utilizing Joseph R.'s suggestion one can use the regex [^/]$ to grep for the files by looking for lines not ending with /.

tar tzf archive.tar.gz | grep -e "[^/]$"

  • That still outputs foo/bar as opposed to just bar. You want grep -Eo '[^/]+$' (with GNU grep). – Stéphane Chazelas May 26 '15 at 15:52

With pax (the POSIX command to read tar files):

pax -'s@.*/@@' < file.tar

(that lists all files regardless of their type, including directories).

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.