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'
Add a comment
|
1 Answer
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.
2 Comments
user3145909
I tried both options but I get the following error. option not availible on this NT BASH release
Joseph Quinsey
@user3145909: I'm not familiar with the NT bash (seems to be based on bash 1.14.2). But I think
sed "s_${STR1}_${STR2}_g" <Try1.txt should work on almost any Unix-like shell. Do we need the -e switch for sed (which is often optional)?