I need to insert a debugging instruction after every catch in a project that contains thousands of PHP files.
I want to match the pattern
catch (
So that after every matching pattern, I want to insert the instruction:
Reporter::send_exception($e);
I've been trying to use sed to accomplish this, but I haven't been able to succeed.
This is the sed command that I'm using:
sed -e '/catch \(/{:a,n:\ba;i\Reporter::send_exception\(\$e\);\g' -e '}' RandomFile.php
Any help writing this will be greatly appreciated!
I've seen other solutions for the same problem here in Stack Overflow, but none of those solution have worked either.
Thanks
EDIT
Basically my files will look like pretty much like this:
try {
do_something();
} catch ( AnyKindOfException $e) {
Reporter::send_exception($e); // Here's where I want to insert the line
// throws generic error page
}
That's why I want to match catch \(*$
and after that insert
Reporter::send_exception($e)
You can do it with sed \a command which allows you to append the line. Syntax is:
sed '/PATTERN/ a\
Line which you want to append' filename
So in your case it would be:
sed '/catch (/ a\
Reporter::send_exception($e);' filename
$ cat fff
adfadf
afdafd
catch (
dfsdf
sadswd
$ sed '/catch (/ a\
Reporter::send_exception($e);' fff
adfadf
afdafd
catch (
Reporter::send_exception($e);
dfsdf
sadswd
I presume you want to insert the text after the line containing catch (.
Under perl -p, $_ contains the line read, and whatever $_ contains after the code is executed will be printed. So we just append the line to insert to $_ when appropriate.
perl -pe'$_.=" Reporter::send_exception(\$e);\n" if /catch \(/'
or
perl -pe's/catch\(.*\n\K/ Reporter::send_exception(\$e);\n/'
Usage:
perl -pe'...' file.in >file.out # From file to STDOUT
perl -pe'...' <file.in >file.out # From STDIN to STDOUT
perl -i~ -pe'...' file # In-place, with backup
perl -i -pe'...' file # In-place, without backup
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With