How to pass special character string to sed [duplicate]

冷暖自知 提交于 2020-04-17 22:50:21

问题


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 

回答1:


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



来源:https://stackoverflow.com/questions/60567208/how-to-pass-special-character-string-to-sed

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!