-1

I'm attempting to find/replace a string found in a number of files spread throughout a directory tree.

I thought I'd use sed for this task.

find /some/dir -name \*.php -exec sed -i "s/cybernetnews/cybernet/g" {} \;

This works as expected with the sample string "cybernetnews", but things get weird when I try to find/replace against this string:

preg_match($_SESSION['infos']['num'], $numeric_variable)

Where I want to replace the string $_SESSION['infos']['num'] with the constant INFOS_NUM.

So I thought this would work:

find /some/dir -name \*.php -exec sed -i "s/$_SESSION['infos']['num']/INFOS_NUM/g" {} \;

No luck, here is what shows in the test php file after running the above command:

preg_match($_SESSION['INFOS_NUMfoINFOS_NUM][INFOS_NUMum'], 
           $INFOS_NUMmeric_variable)

I tried escaping the single quote but get the exact same result. If I escape the bracket, no changes are made.

What character(s) is sed getting hung up on, and how do I properly escape it?

Grijesh Chauhan
  • 57,103
  • 20
  • 141
  • 208
a coder
  • 7,530
  • 20
  • 84
  • 131
  • possible duplicate of [Sed - replacing a string with a variable full of weird characters](http://stackoverflow.com/questions/21535046/sed-replacing-a-string-with-a-variable-full-of-weird-characters) – NeronLeVelu Feb 12 '15 at 06:47
  • Please explain the downvote. – a coder Feb 12 '15 at 18:41

1 Answers1

2

$, [, ] are regex special characters , you must need to escape that in the regex in-order to match those characters literally. To do a case-insensitive match, you need to add i modifier at the last.

find /some/dir -name \*.php -exec sed -i "s/\$_SESSION\['infos'\]\['num'\]/INFOS_NUM/g" {} \;
Avinash Raj
  • 172,303
  • 28
  • 230
  • 274
  • 1
    To add to this, `$` is a special character as well. It's escaped correctly in the snippet, it just wasn't mentioned. – Agop Feb 12 '15 at 00:45