Under my current directory, I have two sub-directories:

   - file1.png
   - file2.png
   - fileN.png

   - fileA.txt
   - ...
   - fileZ.txt

When I tar compress the two directories by :

tar -cvzf result.tar.gz dir_1/ dir_2/ 

I got result.tar.gz but it maintains the directory structure. I mean when I extract the result.tar.gz, I got dir_1 & dir_2 again.

How can I tar compress so that the directory structure is not remained, which means when I extract the tar.gz file, I only get files


2 Answers 2


I think you can do this with the -C option.

From the tar man page:

-C directory, --cd directory, --directory directory
    In c and r mode, this changes the directory before adding the following files.
    In x mode, change directories after opening the archive but before extracting
    entries from the archive.

This means that you should be able to run

tar cvzf result.tar.gz -C /path/to/dir1/ . -C /path/to/dir2/ .

to achieve what you want.

  • I got error "tar: could not chdir to 'dir1/file1.png'"
    – user842225
    Jun 12, 2014 at 12:11
  • I am guessing you missed the spaces between the directory name and the asterisk (*). If we replace all spaces by underscores it should look like this: tar_cvzf_result.tar.gz_-C_dir1/_*_-C_dir2/_*
    – arnefm
    Jun 12, 2014 at 12:13
  • Then I got error "tar: dir1: Cannot stat: No such file or directory"
    – user842225
    Jun 12, 2014 at 12:26
  • 3
    @user842225 That's because the directory paths are relative, you need to either prepend ../ to the second one or use absolute paths. Also you can't use * because it would expand to the list of files in the current directory, you can use . instead. Jun 13, 2014 at 1:41
  • Yes, gilles is correct, that is why my example uses absolute paths. Using relative paths with tar -C tends to get confusing.
    – arnefm
    Jun 18, 2014 at 17:21

With GNU tar, you can use the --transform option to rewrite file names when adding or extracting them to/from an archive. With BSD tar or with pax, the option -s does the same thing.

To remove the leading directory component (so that dir_1/subdir/somefile is stored as subdir/somefile):

tar -czf result.tar.gz --transform '!^[^/]*/!!' dir_1 dir_2

To remove all directory components (so that dir_1/subdir/somefile is stored as somefile):

tar -czf result.tar.gz --transform '!^.*/!!' dir_1 dir_2

You must log in to answer this question.

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