0

I'm trying to do a complex find and replace in all files through unix command line using the answer provided in find and replace in multiple files on command line but I can't seem to get my find and replace strings escaped properly.

I need to find all lines that contain:

if ($session['test']>0){

and replace it with

if ($session['test']>1){

The command I'm trying is:

find . -name '*.php' |xargs perl -pi -e 's/if\(\$session\[\'test\'\]\>0\){/if\(\$session\[\'test\'\]\>1\){/g'

But that gives me another prompt which requires me to enter an additional ' character because the command tells me there's a string that's missing termination. If I put it in extra ' at the end, I get:

Unmatched ) in regex; marked by <-- HERE in m/if\(\$session\[\test']>0) <-- HERE {/ at -e line 1.

How do I get this replacement to work?

Community
  • 1
  • 1
nmc
  • 8,724
  • 5
  • 36
  • 68

2 Answers2

2

Just use double quotes:

perl -pi -e "s/if\(\$session\[\'test\'\]\>0\){/if\(\$session\[\'test\'\]\>1\){/g"

Moreover, you are missing a space after if and the dollar sign needs to be escaped with three backslashes:

perl -pi -e "s/if \(\\\$session\[\'test\'\]\>0\){/if \(\\\$session\[\'test\'\]\>1\){/g"
                 ^  ^^^                                ^^^
alestanis
  • 21,519
  • 4
  • 48
  • 67
  • 1
    Using double quotes results in a successful run of the command but doesn't achieve the replacement I intended. – nmc Mar 08 '13 at 17:18
2

Using double quotes and double escaping the $ works:

perl -pi -e "s/if \(\\\$session\['text'\]>0\){/if (\\\$session['text']>1){/"

A shorter but dirtier solution with a look-behind and look-ahead assertions:

perl -pi -e 's/(?<=if \(\$session\[.text.\]>)0(?=\){)/1/'
mob
  • 117,087
  • 18
  • 149
  • 283