由于要经常更换多个文件夹中多个文件,原文件还要备份一下,每次手动很麻烦,所以花了点时间东拼西凑了一个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}"