shell脚本批量替换并备份原文件

由于要经常更换多个文件夹中多个文件,原文件还要备份一下,每次手动很麻烦,所以花了点时间东拼西凑了一个shell脚本
脚本名为gtf.sh
在要被更换的文件的上级(可多级)目录下创立同级目录,放入此脚本和要更换的文件,脚本根据文件名找到重命名原文件进行备份并复制本文件到目标路径。
运行最好加权限
./gtf.sh 备份效果:原文件名+时间
./gtf.sh new 备份效果:原文件名+new+时间

#!/bin/bash
RED='\e[1;31m'
GREEN='\e[1;32m'
NC='\e[0m' 
fth=$(cd `dirname $0`;pwd)
echo -e "${GREEN}start rootpath:$fth${NC}"
try=$1
succ_f=0
function getdir(){
	for file in $1/*
	do
	xin="/*"
	if [ "${1}${xin}" == "$file" ]
	then
		continue
	fi
	if [ "$fth" == "$file" ]	
	then
		continue
	fi
	if test -f $file
	then
		if [ "${file##*/}" == "$2" ]
		then
			echo $file
			rename $file $2 $try	
		fi
	else
		getdir $file $2
	fi
	done

}

function info(){

	mv "$1" "$2"
}
function info1(){
	cp "./${1}" "${2}/"
	if ((!$?))
	then
		echo "Rename and backup ""./${1}"" to ""${2}/""  success!!!"
		let succ_f+=1
	else
		echo -e "${RED}cp ${1} fail!${NC}"
	fi
}



function rename(){
	si="_"
	nowtime=$(date "+%m%d%H%M")
	if  [[ -z ${3} ]]
	then
	filename="${1}${si}${nowtime}"
	else
	filename="${1}${si}${3}${si}${nowtime}"
	fi1	
	mv_fd=`info "$1" "$filename"`
	if ((!$?))
	then
		info1 "$2" "${1%/*}"
	else
		echo -e "${RED}cannot mv:${1}${NC}"
	fi
	
}
curPath=$(dirname $(readlink -f "$0"))
path=$(dirname "$curPath")

for element in `ls`
do
if [ "$element" == "gtf.sh" ]
then
	continue
fi
if test -f $element
then
	getdir $path $element
fi
done
time1=$(date)
echo -e "${GREEN}dealt with : $succ_f all in $time1 ${NC}"

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值