0

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 
user889030
  • 4,353
  • 3
  • 48
  • 51
  • @anubhava ya i have tried that too earlier it not worked , forgot to add in question – user889030 Mar 06 '20 at 15:38
  • There's no parameter passing going on here. You are constructing a `sed` script that will have the value hard-coded into it. – chepner Mar 06 '20 at 15:41
  • since `$_REQUEST` is PHP specific, I'm going to guess you are constructing this from a PHP script, in which case simply dumping user input into a shell script like you are attempting to do would expose you to a world of trouble. Imagine if $_REQUEST['old'] contains `/g" {} + -delete` – Sorin Mar 06 '20 at 15:48
  • @Sorin no am executing command from ssh terminal – user889030 Mar 06 '20 at 15:50
  • @Sorin ya its dangerous :) above you can see NIGHTMARE ! not working , it replaced everything in file , good that i had back of it – user889030 Mar 06 '20 at 15:51
  • @user889030 that's why the gods who created sed -i gave you the option to make a backup `sed -i.orig ..` – Sorin Mar 06 '20 at 15:54
  • @Sorin no it not helped , here i tested : https://repl.it/repls/AlarmedDesertedExam – user889030 Mar 06 '20 at 16:01
  • 1
    @user889030, it helped, but you have additional stuff to escape see also: https://unix.stackexchange.com/questions/32907/what-characters-do-i-need-to-escape-when-using-sed-in-a-sh-script – Sorin Mar 06 '20 at 16:07
  • @tripleee - the duplicate question is wrong, this is the more appropriate duplicate question https://stackoverflow.com/questions/4133286/interpret-as-fixed-string-literal-and-not-regex-using-sed/60569576#60569576 (sorry, got caught in writing the answer and didn't change the duplicate). @user889030 - see also this answer https://stackoverflow.com/a/60569576/939457 - it would eliminate the need for escaping any chars (except `'`) – Sorin Mar 06 '20 at 18:20

1 Answers1

2

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

glenn jackman
  • 238,783
  • 38
  • 220
  • 352