[英]Find and replace inside a string variable using sed command - shell scripting
lets say I have a string variable variable假设我有一个字符串变量变量
var="This line is with OldText"
I want to find and replace the text inside this variable The method that I tried is,我想查找并替换此变量中的文本我尝试过的方法是,
echo $var | sed -i "s/OldText/NewText/g" >> result.log
in this case this gives an error saying "no input files".在这种情况下,这会给出一个错误,说“没有输入文件”。 The expected output is ,
预期输出为 ,
"This line is with NewText"
what is the correct method to do this using sed, awk or any other method.使用 sed、awk 或任何其他方法执行此操作的正确方法是什么。
Using sed
使用
sed
$ var=$(sed "s/OldText/NewText/" <<< $var)
$ echo $var
This line is with NewText
You don't use -i
, as that's for changing a file in place.您不使用
-i
,因为那是为了更改文件。 If you want to replace the value in the variable, you need to reassign to it.如果要替换变量中的值,则需要重新分配给它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.