untar tar file using --strip-components=1

27.9k Views Asked by At

I have a tar file which has multiple folders like this:

code.tar
  bin/
    startup.sh
  WebServer/
    appname
    webappname
  Configuration/
    a.properties
    b.properties

If I unzip code.tar, I get a folder name code with all the folder structure under it, but I want to extract the contents of code.tar and just get the sub-folder structure under it (ie bin/, WebServer/, configuration/ and files in these folders).

When I use tar -xzf code.tar -C <path> --strip-components=1 I get all the contents of subfolders ie startup.sh,appname etc along with the sub-folders-

eg on running above command I get all these folders and files at same level-

bin/
startup.sh
WebServer/
appname
webappname
Configuration/
a.properties
b.properties

please help

2

There are 2 best solutions below

2
On

There's no explicit flag to allow tar to only extract the files at that depth and not the files any deeper (which is what I'm interpreting the question to mean); Generally you would need to explicitly specify what's to be extracted; e.g.

tarfile="foo.tar.xz"
tar -xf "$tarfile" --strip-components=1 $(tar tf $tarfile | awk -F/ '{if (NF <= 2 && $NF != "") print; }')

We use the list of entries from tar (tar tf) and filter through awk, where when we find any entries with <= 2 items, and that isn't a directory ($NF != "") then we print them.

This will give you all the files that need to be extracted from the archive, which is then passed to an explicit extraction command.

0
On

Your command seems right.

Suppose you have folder "extract" you want to extract the file to:

tar -xzf code.tar -C extract --strip-components=1

So this will truncate the upper folder "code" and just extract the contents with the file-folder structure preserved.