How to replace the following pattern in a java project
catch(SQLException e) {
\\TO DO
}
with
catch(SQLException e) { S.O.P(); }
Please note that the file will have other patterns like
catch(IOException e) {
// To Do }
which should not be changed.
I tried
sed 's/catch\(SQLException[^\}]*}/catch(SQLException e)\{S.O.P();\}/g' file.java
but it does not work.
you can use awk
$ more file
catch(SQLException e) {
\\TO DO
}
catch(IOException e) {
// To Do }
$ awk -vRS="}" '/catch\(SQLException e\)/{$0="catch(SQLException e) { S.O.P();" }NR{print $0RT} ' file
catch(SQLException e) { S.O.P();}
catch(IOException e) {
// To Do }
Explanation: sEt the record separator to }
. Then check for SQLException
. If found, set the record $0
to the new one. No complicated regex required.
You can use this Perl script:
use strict;
my $file = '';
$file.=$_ while(<>);
$file=~s[catch\s*\(\s*SQLException\s*(\w+)\)\s*\{.*?\}][catch(SQLException $1) { S.O.P(); }]sg;
print $file."\n";
Sample run:
Input file:
try { int a = 0/0; }
catch(SQLException e) {
\\TO DO
}
catch(MyOwnException e){
// MORE THINGS
}
finally{
Result:
try { int a = 0/0; }
catch(SQLException e) { S.O.P(); }
catch(MyOwnException e){
// MORE THINGS
}
finally{