How to pass special character string to sed

user889030 :

Am trying to pass special character string to sed command but no success i tried backslash but no success

sed -i 's/old/new/g' {} +   # working 

sed -i 's/$_REQUEST['old']/$_REQUEST['new']/g' {} +   # not working 
sed -i 's/$_REQUEST[\'old\']/$_REQUEST[\'new\']/g' {} +   # not working 
sed -i "s/$_REQUEST['old']/$_REQUEST['new']/g" {} +  # NIGHTMARE ! not working 
glenn jackman :

It's not possible to include single quotes inside a single quoted string, not even by escaping them.

And with double quotes, the shell will expand the $_REQUEST variable (probably substituting the empty string).

Try this:

sed -i 's/\$_REQUEST\['\'old\''\]/$_REQUEST['\'new\'']/g' {} + 
# ...................^^...^^..............^^...^^

Those are the literal single quotes placed outside the single quoted string chunks.

Or, escape the dollars inside double quotes:

sed -i "s/\\\$_REQUEST\\['old'\\]/\$_REQUEST['new']/g" {} +
# ,.......^.................^.

Edited to include the escapes required for the regex-special characters in the left-hand side

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=28188&siteId=1