使用shell脚本进行Java代码格式化
发布时间:2020-12-16 01:34:44 所属栏目:安全 来源:网络整理
导读:我知道这很傻但我不能克服好奇心.是否可以编写一个 shell脚本来格式化一段 java代码? 例如,如果用户在代码中写入: public class Super{ public static void main(String[] args){ System.out.println("Hello world"); int a=0; if(a==100) { System.out.pr
我知道这很傻但我不能克服好奇心.是否可以编写一个
shell脚本来格式化一段
java代码?
例如,如果用户在代码中写入: public class Super{ public static void main(String[] args){ System.out.println("Hello world"); int a=0; if(a==100) { System.out.println("Hello world"); } else { System.out.println("Hello world with else"); } } } 我想写一个shell脚本,它会使代码像这样. public class Super { public static void main(String[] args) { System.out.println("Hello world"); int a=0; if(a==100){ System.out.println("Hello world"); } else{ System.out.println("Hello world with else"); } } 确切地说,我们应该改变花括号的格式.如果是try / catch或控制结构,我们应该将它改为同一行,如果它是函数/方法/类,它应该在下一行.我对sed和awk知之甚少,它可以很容易地完成这个任务.我也知道这可以用eclipse完成.
好吧,我手上有空闲时间,所以我决定重温我过去的好日子:
在阅读了一些关于awk和sed的内容之后,我决定使用它们可能会更好,因为在awk中添加缩进并在sed中解析字符串更容易. 这是格式化源文件的?/ sed_script: # delete indentation s/^ +//g # format lines with class s/^(.+class.+) *({.*)$/1n2/g # format lines with methods s/^(public|private)( +static)?( +void)? +(.+(.*)) *({.*)$/123 4n5/g # format lines with other structures /^(if|else|for|while|case|do|try)([^{]*)$/,+1 { # get lines not containing '{' # along with the next line /.*{.*/ d # delete the next line with '{' s/([^{]*)/1 {/g # and add '{' to the first line } 这是添加缩进的?/ awk_script: BEGIN { depth = 0 } /}/ { depth = depth - 1 } { getPrefix(depth) print prefix $0 } /{/ { depth = depth + 1 } function getPrefix(depth) { prefix = "" for (i = 0; i < depth; i++) { prefix = prefix " "} return prefix } 你就这样使用它们: > sed -f ~/sed_script ~/file_to_format > ~/.tmp_sed > awk -f ~/awk_script ~/.tmp_sed 它远非正确的格式化工具,但我希望它可以作为参考示例脚本正常:]祝你学习顺利. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |