MacOS – Using “tar” command in Terminal for multiple folders/files

macostarterminal

I have many files like these

SomeDirectory/RandomName.spa
SomeDirectory/AnotherRandomName.spa
SomeDirectory/YetAnotherRandomName.spa

I want to unpack every .spa file in SomeDirectory to their each seperate folders, with the same name. I would use something like – tar -xvf, but with what attributes?

Afterwards I want to pack every folder in SomeDirectory again back to RandomName.spa, (keeping the name of folder). The command would be tar -cvf, but with what attributes?

Best Answer

Assuming that (1) the .spa files are actually .tar archives, (2) you are in SomeDirectory, and (3) that directories with the names of the archives you want to extract do not exist, the following piece of code should achieve what you want:

for a in *.spa
  do a_dir=`expr $a : '\(.*\).spa'`
  mkdir $a_dir
  tar -xvf $a -C $a_dir;
done

Or in case you prefer a one-liner:

for a in *.spa; do a_dir=`expr $a : '\(.*\).spa'`; mkdir $a_dir; tar -xvf $a -C $a_dir; done

The first line in the for loop strips the .spa from the archive name and assigns it to a variable, which is used in the second line to make a directory with that name, and in the third line in tar with the -C argument.

The -C argument in tar only changes directory during extraction and doesn't actually make one, making things a a bit more complicated than they should be.

Credit: This answer is a slight modification of https://superuser.com/a/748567/226246