0

I have a certain php code comment that appears in about 75 files across several users. This command succsessfully locates it. (I didn't bother looking for the double slashes because I wasn't sure about escaping them and they really don't matter for this match.)

grep -l -r "calls the myfunc() function" /home/*/public_html   

After I find it, I need to add a line break and some more php code like

if($my_return_var===false){echo "<b>THERE WAS AN ERROR</b>";}

I also need to do similar, like

grep -l -r "include('path/to/my/file.php')" /home/*/public_html   

and then insert BEFORE it

"$my_return_var="

Searching Google, I found that grep piped to sed is probably the way to go, but I'm not sure of the syntax.

Can anyone help? By the way, this q/a is probably close, but still a little over my head. How to replace a text string in multiple files in Linux

TecBrat
  • 183

2 Answers2

2

First thing: make a backup!

Second thing: make a backup!

Since I know perl much better than python, I'd use the perl solution.

Remember that "\n" is a newline in perl, so, something like:

grep -l -r "calls the myfunc() function" /home/*/public_html |xargs perl -pi -e 's/(calls the myfunc() function;)/$1\n if($my_return_var===false){echo "<b>THERE WAS AN ERROR</b>";}/'

I have obviously not tested this, and that's a brute force way to do it (and assumes a bunch of things, e.g., the grep doesn't return filenames with spaces in them and so on). If your search/replace patterns contain "/", you can use an alternative delimiter to your pattern, e.g., s?(calls the myfunc() function;)?$1\n if($my_return_var===false){echo "<b>THERE WAS AN ERROR</b>";?'

cjc
  • 25,492
2

sed can do inserts and appends when it sees a pattern:

grep -l -r "calls the myfunc() function" /home/*/public_html |
xargs sed -i '/calls the myfunc() function/a\
if($my_return_var===false){echo "<b>THERE WAS AN ERROR</b>";}
'

grep -l -r "include('path/to/my/file.php')" /home/*/public_html |
xargs sed -i "/include('path\\/to\\/my\\/file.php')"'/i\
"$my_return_var="
'