之前有一个朋友问过我,如何把当前目录下所有的tar.gz文件分别解压到以该压缩文件命名的文件夹中,且文件夹不带“.tar.gz”。
由于当时对数据流重定向还不算太熟悉,未能帮得上忙。
现在想起来,解决的方法其实很简单:
假设当前目录下有universe.tar.gz,galaxy.tar.gz,solar.tar.gz三个文件:
大概的步骤是:把三个文件名赋值给变量filename,然后使用for … in …循环进行mkdir和解包:
1 2 3 4 5 6 7 8 9 10 |
#!/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,并且支持选择压缩文件类型:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 |
#!/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打包没压缩的类型我还没加进去。也有很多需要完善的地方。如果各位高人有兴趣,拿来修改修改吧。
Comments are closed.