Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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?

share|improve this question
    
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
    
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
add comment

2 Answers 2

up vote 3 down vote accepted

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.

share|improve this answer
    
Pretty nice work with awk :) –  Eero Aaltonen Nov 15 '13 at 13:37
add comment

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.

share|improve this answer
    
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
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.