Thursday, May 6, 2010

Inflate multiple files with one command

If you have many multiple archives which have been compressed using different encryptions (tar, tar.gz or zip) in one directory, you can use the script provided in this post to inflate them into the directories with the same name as the original archive, that is:

file1.zip will get inflated to file1/
file2.tar will get inflated to file2/
file3.tar.gz will get inflated to file3/

So here is the script:

#!/bin/bash

cd $1

for i in $(ls)
do
dir_name=$(echo $i | sed "s/\([^.]*\)[.].*/\1/")

if [[ "$i" =~ "zip" ]]; then
mkdir -p $dir_name
cd $dir_name;
unzip $i
cd ../
elif [[ "$i" =~ "tar.gz" ]]; then
mkdir -p $dir_name
cd $dir_name
tar -xzvf ../$i
cd ../
elif [[ "$i" =~ "tar" ]]; then
mkdir -p $dir_name
cd $dir_name
tar -xvf ../$i
cd ../
fi
done

The argument to this code is the full path of the directory that contains the archived files. Notice that the script searches for the strings, "tar", "zip" and "tar.gz" in the filenames. If you have other files in the directory which contain these strings in their names, they can get overwritten!

You can save the script using a name of your choice (I have named it open.sh, as indicated in the terminal output shown below)

terminal$ ls directory_path/
file1.tar file2.zip file3.tar.gz
terminal$ ./open.sh directory_path/
terminal$ ls directory_path/
file1 file1.tar file2 file2.zip file3 file3.tar.gz

I would like to thank Girish Venkatasubramanian for advice on this script.