If I wanted to find and replace a line with a user input value that has forward slash, then how to do it?
For example I have a script called ./configure.sh which will ask for user to input some path (let's say WPS_HOME). I can read that user input and want to put this value to a configuration file by searching for a string and replace that entire line with user input value. Using following command I can get this working with hard coded value,
sed "s/WPS_HOME.*/WPS_HOME=\/opt\/WebSphere/g" $SPLFRAMEWORK_HOME/environment/splsetupCmdLine.sh > $SPLFRAMEWORK_HOME/environment/splsetupCmdLine.sh_Temp
mv $SPLFRAMEWORK_HOME/environment/splsetupCmdLine.sh_Temp $SPLFRAMEWORK_HOME/environment/splsetupCmdLine.sh
However if the user input value is stored into a variable called WPS_HOME and then use this variable to replace....
sed "s/WPS_HOME.*/WPS_HOME='"$WPS_HOME"'/g" $SPLFRAMEWORK_HOME/environment/splsetupCmdLine.sh > $SPLFRAMEWORK_HOME/environment/splsetupCmdLine.sh_Temp
mv $SPLFRAMEWORK_HOME/environment/splsetupCmdLine.sh_Temp $SPLFRAMEWORK_HOME/environment/splsetupCmdLine.sh
This does not work. It will throw error
sed: 0602-404 Function s/WPS_HOME.*//opt/websphere/ cannot be parsed.
Can anyone suggest solving this problem? I cannot use perl here, any solution using sed or awk is fine.
Yes, it will work, but what will be in case if the variable is taking from user which is a valid UNIX path that contains / and need to put that variable by replacing the corresponding value to other file or value? Any idea?
Delimiter separating ( / ) search pattern and replace pattern need not be ' / ' always, if there is ' / ' character in the input, you could change the delimiter
The use of "/" to delimit regular expressions is not a rule, just a convention. You could use any other character as long as you are consistent to yourself: "s/x/y/g" is the same as "s:x:y:g", but "s/x:y:g" won't work because once you have used a delimiting character in a regexp you have to stick with it.
Anyways, it is a good idea to escape certain characters anyways, regardless of having a workaround with other delimiting chars or not. Therefor it is advisable to have a separate sed-script modify the input before feeding it to further sed-scripts:
"s/[/\.]/\\&/g"
will "escape" any of the characters "\", "/" and "." by putting a backslash ("\") in front of them. Notice, though, that some backslashes are interpreted by the shell. Play around a bit by trying ("<spc>" is ablank character):
print - "\<spc>" | sed 's/[/\.]/\\&/g'
and modify the string enclosed in the double quotes in the "print -"-statement. Notice, how it changes the behaviour if you remove the space and find out why.