tags:

views:

55

answers:

2

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.

A: 

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{
codaddict
hmm according to OP's definition, `MyOwnException` should not be changed.
ghostdog74
@ghostdog: Thanks for pointing.
codaddict
+1  A: 

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.

ghostdog74
Works fine. Thanks
singhambesh