Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

linux

bash

tar

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.

like image 525
Tikroz Avatar asked Jan 29 '26 23:01

Tikroz


1 Answers

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
like image 138
user000001 Avatar answered Jan 31 '26 16:01

user000001



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!