几个简单shell Demo

本文介绍了两个实用的Shell脚本技巧:一是如何解压多种类型的压缩文件,包括.zip和.tar.gz等;二是如何批量重命名文件,适用于大量文件的名称调整工作。

1.解压

#!/bin/bash 
#解压如 *.zip *.tar *.tar.gz 等压缩文件

ftype="$(file "$1")"
case "$ftype" in
	"$1: Zip archive"*)
		unzip "$1"
		;;
	"$1: Gzip compressed"*)
		gunzip "$1"
		;;
	"$1: POSIX tar"*)
		tar xvf $1
		;;
	"$1: gzip compressed"*)
		tar xzvf $1
		;;
	*)
		echo "file $1 can not be uncompressed"
esac




2.对多个文件重命名的简单版本

#!/bin/bash 

#we have less than 3 arguments. Print the help text:
if [ $# -lt 3 ]; then
cat << HELP
ren--renames a number of files using sed regular expressions USAGE:ren 'regexp'
'replacement' files...
EXAMPLE rename all *.HTM files in *.html;
	ren 'HTM' 'html" *.HTM
HELP
fi

old="$1"
new="$2"

#the shift command removes one arguments from the list of command line arguments.
shift
shift
# $@ new contains all the files
for file in "$@"; do
	if [ -f "$file" ]; then
		newfile=`echo "$file" | sed "s/${old}/${new}/g"`
		if [ -f "$newfile" ]; then
			echo "ERROR: $newfile exists already"
		else
			echo "renaming $file to $newfile"
			mv "$file" "$newfile"
		fi
	fi
done

3.对多个文件进行重命名,版本2

#!/bin/bash 
#用途:重命名所有 *.jpg *.png 
#格式为: image1.jpg image2.jpg image3.png等

count=1
for img in *.jpg *.png; do
	new=image-${count}.${img##*.}

	mv "$img" "$new" 2>/dev/null 
	if [ $? -eq 0 ]; then
		echo "rename $img to $new"
		#((count++))
		let count++
	fi
done





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值