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

做~自己de王妃 提交于 2020-01-25 13:07:22

问题


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.


回答1:


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.




回答2:


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{


来源:https://stackoverflow.com/questions/3931887/how-to-replace-catch-block-in-java-using-sed

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!