-1

In OS X, double click X.tgz will generate a folder namedX, putting all files into the folder (the folder name follows the .tgz file's name).

I want to do the same thing in the terminal.

However, tar -xvzf /pathtofile/X.tgz will extract all files and put them in /pathtofile/.

And by tar -xvzf /pathtofile/X.tgz -C /newpath/ the newpath does not automatically follows the .tgz file name(i.e. in this case a folder named "X").

Does anyone know if there is a simple way to do this?

K.J
  • 25
  • 7
  • SO Is not the place for this kind of questions, try SuperUser, Unix & Linux Stack Exchange or maybe even man tar – Ulises André Fierro Aug 01 '17 at 16:23
  • SO users may not welcome this kind of comments. Good programmers do not have the "superiority complex". Post related and helpful answers/comments or you shall try another website. – K.J Aug 01 '17 at 19:02
  • Actually, the site is full of this kind of comments. The point is not to make you feel bad about your question, but to direct you to the right place. Your question is off topic and is vaguely related (if any) to programming. Again, that's why other Stack communities exist and you'll be better of asking there. – Ulises André Fierro Aug 01 '17 at 19:56
  • Well, thanks for your suggestion anyway. I would say a clumsy but possible solution could be bash code which replaces the location folder name with the file name. And the point is I won't feel bad about posting this question because the question exists and I didn't find a solution. And also I could and I do think people could feel a certain allusively disparaging something with regard to your first comment. – K.J Aug 01 '17 at 22:24
  • I've answered your question based off of your most recent comment. This has been asked before and the answer gives you a great head start on what needs to be done (Please read https://stackoverflow.com/questions/15007947/extract-files-contained-in-archive-tar-gz-to-new-directory-named-archive) – Ulises André Fierro Aug 01 '17 at 22:48

2 Answers2

0

Use the strip-component flag in tar:

tar --strip-components=1
Raman Sailopal
  • 12,320
  • 2
  • 11
  • 18
  • First, thanks for the help. the flag "Remove the specified number of leading path elements. ", it seems that it does not add elements to the path. I tried both `tar *.tgz --strip-components=-1` and `tar *.tgz --strip-components=1`, but still get the same result as described. – K.J Aug 01 '17 at 19:22
0

This bash function does what you asked to do, which is basically just creating the directory using the filename without the ".tgz"

extract_to_dir () {
    filename=$1
    dirname="${filename%.*}"
    mkdir ./$dirname
    tar -xvzf $filename -C $dirname
}

Usage would be:

extract_to_dir filename.tgz