freeBSD递归替换包含指定字段的文件名及文件内容

#!/bin/sh
if [ ! $1 ]; then
	echo need dist directory parameter
	exit 1
fi
 
original='oldWord'
newvalue='newWord'
 
changename() {
	name=$1
	ss=`echo $name |grep $original`
	if [ $ss ]; then
		echo changename: $name
		echo $name > name.txt
		sed -i '' "s/$original/$newvalue/g" name.txt
		newname=`cat name.txt`
		mv $name $newname
		fullpath=$newname
	fi
}
getfile(){
    for e in `ls $1`
    do
        fullpath=$1/$e
 
        changename $fullpath
 
        echo $fullpath
 
        if [ -f $fullpath ]; then
            sed -i '' "s/$original/$newvalue/g" $fullpath
        elif [ -d $fullpath ]; then
            getfile $fullpath
        fi  
    done
}
 
read -p "Are you want to change filecontent?[Y]:" flag
if [ "$flag" == "Y" ]; then
    cd $1
    getfile .
# rm -rf name.txt
fi

1.将此代码存为test.sh文件,赋执行权限:chmod 777 test.sh

2.执行test.sh:./test.sh /filefoldpath/,回车后输入Y

3.进行替换的文件会在name.txt中保存对应修改日志

4.如果系统为redhat或者centerOS,则替换第一行#!/bin/sh为#!/bin/bash,替换changename、getfile 函数中的  sed -i '' "s/$original/$newvalue/g" name.txt  替换为  sed -i "s/$original/$newvalue/g" $fullpath,顺序执行 1、2、3步即可实现替换包含“oldword”的文件内容或文件名为“newword”

©️2020 CSDN 皮肤主题: 编程工作室 设计师:CSDN官方博客 返回首页