How to replace catch block in *.java using sed?

2019-08-24 05:50发布

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.

标签: unix shell sed awk
2条回答
戒情不戒烟
2楼-- · 2019-08-24 06:10

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.

查看更多
够拽才男人
3楼-- · 2019-08-24 06:12

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{
查看更多
登录 后发表回答