一、批量替换指定文件种的字符串
sed -i s/oldstring/newstring/g filename
例如:
替换jmx文件中 /root/ 为${__P(user.properties,)}${__P(file.separator,)}csvdata${__P(file.separator,)}
正确写法:
1)
sed -i s'@/root/@${__P(user.properties,)}${__P(file.separator,)}csvdata${__P(file.separator,)}@g' ./3_organization_secondarySelectList.jmx
2)
sed -i s'/\/root\//${__P(user.properties,)}${__P(file.separator,)}csvdata${__P(file.separator,)}/g' ./4_organization_subordinateSelectList.jmx
3)
sed -i s'/\/root\//${__P(user.properties,)}${__P(file.separator,)}csvdata${__P(file.separator,)}/g' ./4_organization_subordinateSelectList.jmx
4)
sed -i 's/\/root\//${__P(user.properties,)}${__P(file.separator,)}csvdata${__P(file.separator,)}/g' ./6_authentication_auth.jmx
错误的写法:
下面的写法默认$后面的是变量,如果没有找到变量的值会报错
sed -i s"/\/root\//${__P(user.properties,)}${__P(file.separator,)}csvdata${__P(file.separator,)}/g" ./5_config_button.jmx
二、替换目录下所有文件中字符串
1)sed -i s'/\/root\//${__P(user.properties,)}${__P(file.separator,)}csvdata${__P(file.separator,)}/g' `grep \/root\/ -rl ./`
``反引号:将反引号内的linux命令先执行,输出被放入主命令,主命令再被执行
grep参数:
-l 列出文件内容符合指定的范本样式的文件名称
-r或--recursive 此参数的效果和指定“-d recurse”参数相同
-d 或--directories=<进行动作> 当指定要查找的是目录而非文件时,必须使用这项参数,否则grep指令将回报信息并停止动作。
2) 将当前目录下文件中的D:/ 替换为${__P(user.properties,)}${__P(file.separator,)}csvdata${__P(file.separator,)}
sed -i s'/D:\//${__P(user.properties,)}${__P(file.separator,)}csvdata${__P(file.separator,)}/g' `grep D:/ -rl ./`
参考:
linux替换目录下所有文件中的某字符串
比如,要将目录/modules下面所有文件中的zhangsan都修改成lisi,这样做:
sed -i “s/zhangsan/lisi/g” grep zhangsan -rl /modules
解释一下:
-i 表示inplace edit,就地修改文件
-r 表示搜索子目录
-l 表示输出匹配的文件名
这个命令组合很强大,要注意备份文件
使用sed命令可以进行字符串的批量替换操作,以节省大量的时间及人力;
使用的格式如下:
1
sed -i “s/oldstring/newstring/g” grep oldstring -rl path
其中,oldstring是待被替换的字符串,newstring是待替换oldstring的新字符串,grep操作主要是按照所给的路径查找oldstring,path是所替换文件的路径;
-i选项是直接在文件中替换,不在终端输出;
-r选项是所给的path中的目录递归查找;
-l选项是输出所有匹配到oldstring的文件;
实例:
- 替换指定文件的字符串
sed -i “s/oldstring/newstring/g” filename
sed -i “s/6/sk/g” ./test01.txt
- 字符串替换批量文件操作
sed -i “s/6/sk/g” grep 6 -rl /home/work/test
sed -i “s/6/sk/g” grep 6 -rl /home/work/test/*.sh
参考资料:
https://blog.csdn.net/smilefxx/article/details/84061606