服务器, 未分类

把每个压缩文件解压到以该压缩文件的文件名命名的文件夹中(文件夹名不包含扩展名)

之前有一个朋友问过我,如何把当前目录下所有的tar.gz文件分别解压到以该压缩文件命名的文件夹中,且文件夹不带“.tar.gz”。

由于当时对数据流重定向还不算太熟悉,未能帮得上忙。

现在想起来,解决的方法其实很简单:

假设当前目录下有universe.tar.gz,galaxy.tar.gz,solar.tar.gz三个文件:

三个文件

 

大概的步骤是:把三个文件名赋值给变量filename,然后使用for … in …循环进行mkdir和解包:

#!/bin/bash
#Get the files name.
filesname=$(ls *.tar.gz -a|sed "s/.tar.gz//g")
#for loop
for packname in $filesname
do
mkdir $packname
tar zxvf $packname.tar.gz -C $packname
done
echo "Finished."

当然,这只是一个比较简单的解决方案,其实通过read,能制作出交互式的Shell Script,并且支持选择压缩文件类型:

#!/bin/bash
#loop for tar
function_tarfiles() {
#Get the files name.
filesname=$(ls *.$type -a|sed "s/.$type//g")
for packname in $filesname
do
        echo "Unpacking the $packname.$type."
        mkdir $dir$packname
        tar -z -$compress -f $packname.$type -C $dir$packname||error=1

        if [ "$error" = 1 ];then
                echo "$packname.$type unpack failed."
        fi

done
echo "Finished."
}

#loop for zip
function_zipfiles() {
#Get the files name.
filesname=$(ls *.$type -a|sed "s/.$type//g")
for packname in $filesname
do
        echo "Unpacking the $packname.$type."
        mkdir $dir$packname
        unzip $packname.$type -d $dir$packname||error=1

        if [ "$error" = 1 ];then
                echo "$packname.$type unpack failed."
        fi
done
echo "Finished."
}

#Which type?
echo "zip: The pack which use zip command to compress."
echo "tar.gz: The pack which use tar command and gzip compress."
echo "tar.bz2 The pack which use tar command and bzip2 compress."
read -p "What are the packaging type of your pack?(zip or tar.gz or tar.bz2):" type
read -p "Where would you like to save the unpack files?(Do not foget the / at last. eg. /home/unpack/):" dir
if [ "$type" = "zip" ];then
        function_zipfiles
elif [ "$type" = "tar.gz" ];then
        compress=x
        function_tarfiles
elif [ "$type" = "tar.bz2" ];then
        compress=j
        function_tarfiles
else
echo "Wrong type."
exit 1
fi

虽然加了挺多的功能,但是我觉得我这样写有点复杂。只用tar打包没压缩的类型我还没加进去。也有很多需要完善的地方。如果各位高人有兴趣,拿来修改修改吧。

102 Posts

自信、努力、活出精彩;以前未所见的颜色,绘大千世界!
View all posts

4 thoughts on “把每个压缩文件解压到以该压缩文件的文件名命名的文件夹中(文件夹名不包含扩展名)”

Leave a reply

Your email address will not be published. Required fields are marked *