How do you untar multiple files into multiple subdirectory based on filename

Viewed 137

I have a single tar file containing files (no folders)

0000107b869682826003b04a40e6394.txt
00029237482s8923789423ud8923892.txt
2c002y8378723887292377a79237649.txt
f598238209237408238742308374038.txt

how do I untar all the files such that they appear in subdirectories named after the first two chars of the files. So for the example above, it would create 00, 2c, and f5 directories and each would have the following files.

00\0000107b869682826003b04a40e6394.txt
00\00029237482s8923789423ud8923892.txt
2c\2c002y8378723887292377a79237649.txt
f5\f598238209237408238742308374038.txt
1 Answers

Iterate over the contents of the archive with tar -tf archive.tar, then use tar -C to extract the files in the desired directory:

while read -r f; do
    mkdir -p ${f:0:2} && tar xf archive.tar -C ${f:0:2} $f
done < <(tar -tf archive.tar)
Related