How can I extract a file from a tar archive without creating the subdirectories?

4.7k Views Asked by At

I have a compressed tar archive and I want to extract one file from deep in the archive to the current working directory.

Is there something better than tar, or a way to extract it without the directory components?

I'm doing something like this right now:

tar xfvz $file -C $destination $folder"/"$file
cd $destination"/"$folder
mv $file ../$file 
rm -r $folder

But I sometimes delete the wrong $folder.

For example, my archive is : mytar.tar.gz. Inside it I have myfolder/mysecondfolder/hello.txt.

I want to extract myfolder/mysecondfolder/hello.txt as hello.txt in the current directory.

2

There are 2 best solutions below

4
On

Just give the full stored path of the file after the tarball name.

Example: suppose you want file test.tar.gz from 2.pdf:

tar -zxvf test.tar.gz 2.pdf

3
On

If GNU tar is available, you could use the --strip-components parameter:

#!/bin/bash
file_to_extract=myfolder/mysecondfolder/hello.txt
depth=$(awk -F/ '{print NF-1}' <<< "$file_to_extract")
tar zxvf mytar.tar.gz --strip-components="$depth" "$file_to_extract"

From man tar:

--strip-components=NUMBER
      strip NUMBER leading components from file names on extraction

Source: https://www.linuxquestions.org/questions/linux-newbie-8/extracting-tar-gz-files-in-current-directory-689243/#postmenu_3368879


A shorter solution would be to use the --transform option, as suggested by Toby Speight:

tar zxvf mytar.tar.gz --transform='s,.*/,,' myfolder/mysecondfolder/hello.txt