unpack 'tar' but change directory name to extract to

27

9

tar -tf filename.tar
folder1/file
folder1/name
[...]

I'd like to extract file and name to, folder2. Can this be done as a one-liner?

Felipe Alvarez

Posted 2010-05-30T00:32:48.993

Reputation: 1 666

Answers

36

Use -C and --strip-components (See man tar).

Example:

mkdir FOLDER
# for remote tar file
curl -L ’remote_tar_file' | tar -xz - -C FOLDER --strip-components=1

# for local tar file
tar -xzf FILENAME -C FOLDER --strip-components=1

Explanation:

The -C flag assumes a directory is already in place so the contents of the tar file can be expanded into it. hence the mkdir FOLDER.

The --strip-components flag is used when a tar file would naturally expand itself into a folder, let say, like github where it examples to repo-name-master folder. Of course you wouldn’t need the first level folder generated here so --strip-components set to 1 would automatically remove that first folder for you. The larger the number is set the deeper nested folders are removed.

Marian

Posted 2010-05-30T00:32:48.993

Reputation: 888

I'd upvote this if it gave an example and not just the switches, as the online manual states, 3 argument styles give rise to confusion.

– Iain – 2014-07-22T14:45:59.353

I read man tar. Didn't spot --strip-components. nice one – Felipe Alvarez – 2010-05-30T06:25:35.637

Forgot the -f on tar -xz, me thinks. Failed for me. I thought I'd been using that for no reason all this time... – John Carrell – 2018-12-04T20:14:08.317

When the output of curl is piped into tar, there should be no single hyphen parameter (i.e., instead of -xz - -C it should just read -xz -C). A single hyphen usually acts as a filename and refers to using stdin instead of a file, but without a -f tar already uses stdin without an explicit -. In fact, it does not expect any filename in this case and providing one (even -) will trigger an error. – Zoltan – 2020-01-16T13:24:20.293

1tar-1.14 uses --strip-path, tar-1.14.90+ uses --strip-components. Maybe problem here? – Mikhail Moskalev – 2011-06-26T07:42:44.120

18

You can also use the --transform option for a bit more flexibility. It accepts any sed replacement (s) operation.

For example, this is how I extract a Linux tarball to a new directory so I can apply a patch:

tar -xjf linux-2.6.38.tar.bz2 --transform 's/linux-2.6.38/linux-2.6.38.1/'

Tom

Posted 2010-05-30T00:32:48.993

Reputation: 180