user3145909
user3145909

Reputation: 75

match string with spaces and replace with another similar string with spaces

I have a file named Try1.txt that contains the string
           "End Date     :             "
I have a script named Try1.sh which has the string assigned to a variable
STR1="End Date     :             "
I have a replacement string also assigned to the following variable
STR2="End Date     : Tuesday 05/06/2014"
I want to edit in place the file and replace STR1 with STR2.
I tried several different sed commands but could not figure it out.
I tried sed -i -e "s/$STR1/$STR2/g" <Try1.txt >Try1.out.txt
but it gives me the following error:
sed.exe: -e expression #1, char 49: unknown option to `s'

Upvotes: 2

Views: 126

Answers (1)

Joseph Quinsey
Joseph Quinsey

Reputation: 9952

Your problem is that $STR2 contains a slash /.

Assuming that neither $STR1 nor $STR2 contain an underscore, _, the following will work:

$ sed "s_${STR1}_${STR2}_g" <Try1.txt >Try1.out.txt

Test:

$ STR1="End Date     :             "
$ STR2="End Date     : Tuesday 05/06/2014"
$ echo "$STR1" > Try1.txt
$ sed "s_${STR1}_${STR2}_g" <Try1.txt
End Date     : Tuesday 05/06/2014

If you have no guarantee about not having underscores in your strings, the following also seems to work:

sed "s^A$STR1^A$STR2^Ag" <Try1.txt

where the three ^A's are entered as Cntrl-V Cntrl-A. (Using \x01 doesn't work for me.)

See also, for example, sed search and replace strings containing / and Sed replacement not working when using variables.

Upvotes: 2

Related Questions