I have been trying to replace a string using the sed command
string value contain blackslash and double quotes. I am not a expert writer of unix script but do try not to ask question. I have almost given up. Hope you all can give me some suggestion
I want to replace a place string in a file that contains "TEMP"\1\"/work/tmp" (values are with double quotes) with another value "TEMP"\1\"/work/${projectname}/tmp" (projectname is passed through a list from a file)
example this sting "TEMP"\1\"/work/tmp" needs to be replace like this "TEMP"\1\"/work/AST/tmp" (where is AST is the project name)
command used:-
projectname="AST"
search_string="\"TEMP\""\\1\\"\"/work/tmp\""
replace_string="\"TEMP\""\\1\\"\"/work/${projectname}/tmp\""
sed -e "s|${search_string}|${replace_string}|g" ${ARCH_DIR}/${PROJECT}.DSParams > ${PROJECT_DIR}/${PROJECT}/DSParams
I have tried with different options like using single quotes, parsing but could not find a solution
however the same command is working fine for below
you're very close; your only problem is that variable expansions do not occur inside single quotes. Try:
PROJECT="AST"
search_string='"TEMP"\\1\\"\/work\/tmp"'
replace_string='"TEMP"\\1\\"\/work\/'${PROJECT}'\/tmp"' # Note the added pair of single quotes
sed s#"${search_string}"#${replace_string}#g ${ARCH_DIR}/${PROJECT}.DSParams > ${PROJECT_DIR}/${PROJECT}/DSParams
My approach to sed situations like this is that if there is even a hint of interaction with the shell: quotes: single, double, backtick, escape: backslash, or any of the meta-symbols: dollar sign, question mark, asterisk, parens, braces, brackets, etc., then I place the commands in a file and let sed read that file thus avoiding the shell complications, i.e.
sed -f script-file ... -or-
--file=script-file ...
I t may be the case that a preliminary pass over those commands is necessary -- it looked like you wanted a variable or two evaluated, which, in my opinion would still be easier than trying to get all the escapes, etc, in the correct number and order for the shell.