是否可以使用shell在文件中搜索并替换值?当我安装服务时,我希望能够在配置文件中搜索变量,然后用该值替换/插入我自己的设置。在shell脚本中查找和替换
8
A
回答
20
当然,你可以使用sed或awk来做到这一点。 sed示例:
sed -i 's/Andrew/James/g' /home/oleksandr/names.txt
0
通常使用awk或sed这样的工具。
$ sed -i 's/ugly/beautiful/g' /home/bruno/old-friends/sue.txt
1
您可以用sed来做到这一点:
sed -i 's/toreplace/yoursetting/' configfile
sed的可能是目前在每一个类Unix系统在那里。如果您要更换多个occurence可以在G添加到S-命令:
sed -i 's/toreplace/yoursetting/g' configfile
要小心,因为这会彻底摧毁你的CONFIGFILE如果不正确地指定toreplace价值。 sed还支持搜索和替换中的正则表达式。
3
sed -i 's/variable/replacement/g' *.conf
-1
看那UNIX power tools的awk,sed的,grep的和in-place edit of files用Perl。
6
您可以使用sed执行搜索/替换。我通常是从一个bash shell脚本做到这一点,并移动原始文件包含的值被取代为新的名称,然后运行的sed写输出到我原来的文件名是这样的:
#!/bin/bash
mv myfile.txt myfile.txt.in
sed -e 's/PatternToBeReplaced/Replacement/g' myfile.txt.in > myfile.txt.
如果你不” t指定一个输出,替换将转到stdout。
1
filepath="/var/start/system/dir1"
searchstring="test"
replacestring="test01"
i=0;
for file in $(grep -l -R $searchstring $filepath)
do
cp $file $file.bak
sed -e "s/$searchstring/$replacestring/ig" $file > tempfile.tmp
mv tempfile.tmp $file
let i++;
echo "Modified: " $file
done
+0
你可以在你的代码中检查'输入代码在这里吗?它可能不应该在那里。顺便说一下:在大多数情况下,在解决方案中提供注释是一个好主意,或者至少总结您选择解决问题的方法。 –
相关问题
- 1. 如何查找和替换shell脚本中的文本
- 2. 查找和替换脚本
- 3. shell脚本查找和替换字符串
- 4. 查找和shell脚本
- 5. Shell脚本:替换文本
- 6. 查找和替换 - Google表格脚本
- 7. 批处理脚本查找和替换
- 8. 查找和替换函数的脚本
- 9. 查找和替换为textWrangler脚本
- 10. Shell脚本参数替换
- 11. shell脚本变量替换
- 12. shell脚本查找和在XML
- 13. Shell脚本,搜索和替换变量
- 14. 在bash shell中查找并替换
- 15. shell脚本:搜索/替换和检查文件存在
- 16. Unix shell脚本查找文件并按模式替换名称
- 17. MS Word文档:使用Shell脚本自动查找/替换
- 18. 查找域名并将其替换 - Shell脚本
- 19. 如何使用shell脚本查找和替换属性文件中的属性?
- 20. 查找和替换文本
- 21. CakePHP 1.3:在脚本中查找和替换字词功能
- 22. VB脚本查找和替换Word文档中的文本
- 23. Shell脚本:grep和替代
- 24. 在shell脚本中查找天
- 25. 查找和使用shell脚本
- 26. shell脚本查找,搜索和
- 27. 如何查找和使用shell脚本
- 28. 需要帮助的shell脚本查找和XML文件替换值
- 29. bash shell中的条件查找/替换
- 30. 查找shell脚本错误
当然可以,使用sed! – Mithrandir