首先判断输入的参数是否是两个
查找 所有的xml配置文件 把文件中从头到尾含有参数1($1)全部替换为参数2($2) 使用perl不生成转换过程中的中间文件,执行起来很快 -i参数直接原地编辑文件。
然后把参数1 替换为参数2
#!/bin/bash
if [ $# -lt 2 ]; then
echo pls Input 2 parameter
else
echo replace \"$1\" with \"$2\"
find . -name "*.xml" -print | xargs perl -pi -e "s/$1/$2/g"
fi
exit 0
使用find和sed
#首先查找个数(sed -n)
find . -name '*.htm' | xargs sed -n '/old/p'
#然后替换(sed -i)
使用grep和sed
sed -n '/old/p' `grep -l old *.htm`
使用find和perl
find . -name '*.htm' | xargs perl -pi -e 's|old|new|g'
参考:
http://hi.baidu.com/msingle/blog/item/3b125b3fc0e1efe255e72375.html
http://blog.csdn.net/zhangboyj/article/details/6215429
find . -type f | xargs grep flash
说明:
找出前目录及其子目录下的文件中含有 flash 的文件
//
重点记录下 xargs 命令:
xargs 在标准输入上取得参数列表、一行一个,再将他们以适当的大小组起来(由主机的 ARG_MAX 值决定)传给另一个命令,此命令在作为 xargs 的参数.
ARG_MAX 值查看方法:
getconf ARG_MAX
//
//
在多个文件中查找使用命令替换也可以完成
grep flash $( find . -type f)
说明:
$() 是命令替换,括号内是 shell 命令;shell 执行括号内的命令并将整个 $(...) 替换为 命令的输出
命令替换的形式有两种,一种是 $(),另一种是使用两个反引号 `find . -type f`
// 多个文件中替换 - sed
为了保证不该替换的不被替换,先在文件中查找一下哪些会被替换
find -type f ! -path '*.svn*' | xargs sed -n '/Ookong inc/p'
说明:
1, find 首先过滤掉 .svn 目录及其子目录
2, xargs 传递参数给 sed 命令
3, sed 执行查找, 只打印符合要求的行
//
// 替换
find -type f ! -path '*.svn*' | xargs sed -i 's/Ookong inc/Ookong Ltd. Co./g'
说明:
1, sed 的 i 选项直接在文件中替换,而不是把替换结果打印出来
2, g 对每行中所有匹配执行替换
//
//
另外:一个 perl 多文件查找的程序: ack
-- 显示所在的行号及所在的文件