0
#!/bin/bash 
filename="test.txt"
firstString="Suzi" 
secondString="I love Sara  & Marry"
 # do something...

#The result must be like this:
resultString=I love Sara  & Marry
  • what to do if it contains & in string and i am using this command but it replace & with suzi like i love sara suzi marry

    sed -i "s|${firstString}|${secondString}|g" $filename

ng="I love Sara & Marry"

Toto
  • 89,455
  • 62
  • 89
  • 125
Akash
  • 1
  • 1
  • `what to do if it` see and read https://stackoverflow.com/questions/407523/escape-a-string-for-a-sed-replace-pattern – KamilCuk May 11 '21 at 12:15
  • secondString and resultString are already the same. Did you want to put "Suzi" in there somewhere? – glenn jackman May 11 '21 at 12:37
  • no, i want my final result like "i love sara & Marry" @glennjackman – Akash May 12 '21 at 08:22
  • I've voted to close the question for lack of clarity. `resultString=$secondString` seems to answer the question, but it's clearly not what you want. – glenn jackman May 12 '21 at 12:42

1 Answers1

0

temp=$(printf '%s\n' "$secondString" | sed -e 's/[/&]/\&/g')

sed -i "s|$firstString|$temp|g" $filename

use above commands to search and replace a string in a file, It worked for me.

Akash
  • 1
  • 1