2

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.

2
  • 1
    Remove -i option from it, its for inplace editing and you are Good to go, cheers. Commented May 20, 2022 at 5:48
  • Optionally you could: echo $var >> result.log && sed -i "s/OldText/NewText/g" result.log Commented May 20, 2022 at 10:36

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

Comments

2

Using sed

$ var=$(sed "s/OldText/NewText/" <<< $var)
$ echo $var
This line is with NewText

Comments

2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.