#!/bin/bash
#替换某个目录下的文件 author:huangbaokang
fileDir=$1
sourceStr=$2
targetStr=$3
echo "fileDir="$fileDir
echo "sourceStr="$sourceStr
echo "targetStr="$targetStr
# 遍历当前目录下的所有html文件
function getAllFiles(){
fileList=`ls $1`
for filename in $fileList
do
if [ -f $filename ]; then
## 只处理html文件
if [ "${filename##*.}"x = "html"x ]; then
## 进行字符替换
echo "文件名="$filename
sed -i "s/$sourceStr/$targetStr/g" $filename
fi
else
# echo "目录下的文件名="$filename
getAllFiles $1"/"$filename
fi
done
}
getAllFiles $1
#替换某个目录下的文件 author:huangbaokang
fileDir=$1
sourceStr=$2
targetStr=$3
echo "fileDir="$fileDir
echo "sourceStr="$sourceStr
echo "targetStr="$targetStr
# 遍历当前目录下的所有html文件
function getAllFiles(){
fileList=`ls $1`
for filename in $fileList
do
if [ -f $filename ]; then
## 只处理html文件
if [ "${filename##*.}"x = "html"x ]; then
## 进行字符替换
echo "文件名="$filename
sed -i "s/$sourceStr/$targetStr/g" $filename
fi
else
# echo "目录下的文件名="$filename
getAllFiles $1"/"$filename
fi
done
}
getAllFiles $1
调用方式
./replace.sh /root/hbk/test hbk huangbaokang
第一个参数为目录
第二个参数为源字符串(替换前)
第三个参数为目标字符串(替换后)
并且会输出替换过的文件内容到控制台。
其实更快的一种方式是如下:(夜枫注释:我没看懂怎么使用)
[root@localhost hbk]# cat /root/hbk/test/css/my.html
hbk
hbk
[root@localhost hbk]# find /root/hbk/test -name "*.html" -exec grep "hbk" {} \; -exec sed -i 's/hbk/huangbaokang/g' {} \;
hbk
hbk
[root@localhost hbk]# cat /root/hbk/test/css/my.html
huangbaokang
huangbaokang
hbk
hbk
[root@localhost hbk]# find /root/hbk/test -name "*.html" -exec grep "hbk" {} \; -exec sed -i 's/hbk/huangbaokang/g' {} \;
hbk
hbk
[root@localhost hbk]# cat /root/hbk/test/css/my.html
huangbaokang
huangbaokang