22

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?

Eero Aaltonen
  • 621
  • 1
  • 5
  • 13
  • 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
  • 6
    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

4 Answers4

24

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.

Joseph R.
  • 39,549
8

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 "[^/]$"

PersianGulf
  • 10,850
4

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.

2

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

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

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