Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linux SED search replace multiple per line

I need to replace a whole bunch of PHP super globals in a clients website with a PHP function I made to clean the superglobals from xss attacks.

Here is what the original code might look like:

echo $_REQUEST['HELLO1'] . ' AND ' . $_REQUEST['HELLO2'];

I need it to look like this:

echo MYCLASS::myfunction($_REQUEST['HELLO1']) . ' AND ' . MYCLASS::myfunction($_REQUEST['HELLO2']);

The main issue, I need to do a search/replace on over 100 files! Yikes!

So my solution was this (in linux shell):

sudo sed -i 's/\$_REQUEST[.*\]/MYCLASS::myfunction(&)/g' *.php

This works great as-long-as only one instance of "$_REQUEST" occurs per line... However with multiple instances, it screws up and does this:

echo MYCLASS::myfunction($_REQUEST['HELLO1'] . ' AND ' . $_REQUEST['HELLO2']);
like image 261
Kevin Florida Avatar asked Jan 27 '26 16:01

Kevin Florida


1 Answers

The problem is that .* is greedy and will find the longest possible match it can. To work around that use [^]]* instead so that you don't inadvertently grab up an extra set of square brackets.

sudo sed -i 's/\$_REQUEST\[[^]]*\]/MYCLASS::myfunction(&)/g' *.php

In other regex dialects you could also write .*? to make the wildcard non-greedy, but that doesn't appear to work in sed (at least not in my version, not even with sed -r).

like image 127
John Kugelman Avatar answered Jan 30 '26 05:01

John Kugelman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!