如何使用shell脚本查找和替换文件数据

时间:2015-03-11 04:19:26

标签: bash shell

我的文件名是myfile.txt,我想用shell脚本替换它里面的一些数据。 我想将ScriptPathPC=\Myfile\file_core替换为ScriptPathPC=./file_core/ 我试过的代码是

replace "ScriptPathPC=\Myfile\file_core" "ScriptPathPC=./file_core/" -- myfile.txt

但是这个命令适用于正斜杠[/]而不是反斜杠[]。还有其他解决办法吗?

1 个答案:

答案 0 :(得分:1)

使用替换

replace要求替换为perl-style:

replace 's|ScriptPathPC=\\Myfile\\file_core|ScriptPathPC=./file_core/|' file.txt 

替换命令看起来像s|old|new|。为了防止对它们进行特殊处理,我们必须逃避反斜杠。

使用sed

sed可以同样进行更改。在这里,我们在stdout上显示新文件:

$ sed 's|ScriptPathPC=\\Myfile\\file_core|ScriptPathPC=./file_core/|' myfile.txt 
ScriptPathPC=./file_core/

在这里,我们更改旧文件:

sed -i's | ScriptPathPC = \ Myfile \ file_core | ScriptPathPC =。/ file_core / |' myfile.txt的