-1
tar -xvf company_raw_2012-03-16.tgz --directory=/root/test --strip-components=4

I am using the following tar option to remove the leading directories and it is working as expected.

--strip-components NUMBER
strip NUMBER of leading components from file names before extraction

It works only when I know that there are going to be 4 sub-directories. I have tar files and I do not know if there will be 2, 3 or 4 folders inside. How do I strip the entire path and extract files in the given "directory" path.

3
  • Are you talking about a variable --strip-components number in a single tar archive? If so, if you have files with the same name in different directories in your tar archive, which one will be kept when you extract them?
    – Ladadadada
    Apr 5, 2012 at 10:57
  • The file names will be unique. And there will be exactly 3 files 3 or 4 folders down the line
    – shantanuo
    Apr 5, 2012 at 11:06
  • What will happen if I provide all options using separate tar command? So three commands like --strip-components=3 --strip-components=4 --strip-components=5 # is it OK?
    – shantanuo
    Apr 5, 2012 at 12:05

4 Answers 4

1

You have two options: read the tar file first ( tar tf ) and count the / in the output, then extract; or extract first, then move back all files up and delete empty directories.

Here is one way to achieve the first approach:

tar tf archive.tgz | tail -n1 | perl -ne '@l=split(/\//);print "$#l\n"'

Other methods are left as an exercise for the reader :)

3

You can just extract the tar file as normal without adding the switch --strip-components. Then, you can use the following find command to move all extracted files to some destination directory:

$ find <your_extracted_dir> -type f -exec mv -t /path/to/dest/dir {} \;
0
1
tar --transform 's#.*/\([^/]*\)$#\1#' -xvf <filename>

this will use the regex on the file name and strip all the path from the filename so all files are extracted to the current dir.

2
  • tar: unrecognized option `--transform' ### tar (GNU tar) 1.15.1
    – shantanuo
    Apr 5, 2012 at 11:09
  • @shantanuo tar 1.15.1 does not support the --transform command. it was released in 2004-12-21, recent versions of gnu tar do support the command
    – Sibster
    Apr 5, 2012 at 11:18
0

Inspect the tarball before issuing the extract with --strip-components by using:

tar -tzf filename.tar.gz | less
1
  • I need to use tar command in shell script. less does not help
    – shantanuo
    Apr 5, 2012 at 10:54

You must log in to answer this question.

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