Sed command to replace any type of string in shell script in linux

Hi Team,

I am trying to replace string like below with sed command, but I am not able to replace with new string.

EX: old_String : watt.server.http.Content-Security-Policy=default-src \‘self’\ *.abc.com ..abe.com
New_Sting: watt.server.http.Content-Security-Policy=default-src ‘self’ *.abe.com ..abc.com

sed -i “s~$old_String ~$New_Sting~g” filename.txt

The above sed command is working for other string but not for the above sting.
in old_string \‘self’\ will vary each time, ex: \'self’\, \\\‘self’\\\. The \ can be any number of times it wary each time.

Any inputs would be very helpful.

Hi.
i tried in vain as You did. but could help this construct?:

cat filename.txt # see the content
in old_string .self.\ will vary each time, ex: 'self., \.self.\. The \ can be a
2
in old_string .self.\ will vary each time, ex: 'self., \.self.\ZZ

cat filename.txt | tr -d '' # tr is “translate character”
tr: Warning: Rückschrägstrich () ohne Fluchtzeichen am Ende der Zeichenkette ist nicht portabel
in old_string .self. will vary each time, ex: 'self., .self… The can be a
2
in old_string .self. will vary each time, ex: 'self., .self.ZZ
despite of the warning i got rid of all slashes

regards
Hilmar

1 Like

oops. my original file content multiple slashes
in old_string .self.\ will vary each time, ex: 'self., \.self.\. The \ can be a
2
in old_string .self.\ will vary each time, ex: 'self., \.self.\ZZ

1 Like

sending the message deletes multiple slashes

HI Wantje,

One more approach tried is below grep the exact string of this

string=grep "watt.server.http.Content-Security-Policy=" file_name

EX: output string=watt.server.http.Content-Security-Policy=default-src \‘self’\ *.abc.com . .abe.com

stLine=grep -n "${string}" file_name

The above command will give the exact match line number. Next I am deleting the line number like below

sed -i “${stLine}d” file_name (This will delete the exact matched sting)

Now just add the new string to the file_name.

echo “watt.server.http.Content-Security-Policy=default-src ‘self’ *.abc.com . .abe.com” >> file_name

I hope this also should work right?

Any inputs would be helpful.

Hi

what is going wrong with tr command?

your idea is not clear to me: <<<<<<<<<<<<<< i added 2 comments below

I will also test your case and will let you know, the above one I tested so I updated here.

Once I test it, I will let you know