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.
CodePudding user response:
Using sed
$ var=$(sed "s/OldText/NewText/" <<< $var)
$ echo $var
This line is with NewText
CodePudding user response:
You don't use -i
, as that's for changing a file in place. If you want to replace the value in the variable, you need to reassign to it.
CodePudding user response:
If you are using Bash shell, you could:
$ echo ${var/OldText/NewText}
This line is with NewText
so
$ var=${var/OldText/NewText}
See this for more.