在工作中,经常需要更改文件夹下面所有文件的某些内容时候,我们只需要通过sed -i 's/A/B/g' file,就可以解决了。但是,如果里面嵌套着文件夹,文件夹里面又有文件需要更改内容。这个时候,我们就需要写一个脚本来更改脚本了。代码如下:
#!/bin/sh
function usage(){
echo "usage:sh $0 direc replace_before replace_after"
exit 1
}
function replace(){
#files=`tree -if $1 | grep .*.sh `
files=`find $1 -type f -regex .*.sh`
for file in $files
do
sed -i "s/$2/$3/g" $file
done
RAWVAL=$?
if [ $RAWVAL -eq 0 ];
then
echo "done successfully"
else
echo "done failed"
fi
}
function main(){
if [ $# -ne 3 ]
then
usage
fi
replace $*
}
main $*
如用法是:
sh replace_contents.sh direc/ tom jack
将文件中tom改为jack。