Har*_*ish 6 java unix shell scripting
我知道这很傻但我不能克服好奇心.是否可以编写一个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");
}
}
}
Run Code Online (Sandbox Code Playgroud)
我想写一个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");
}
}
Run Code Online (Sandbox Code Playgroud)
确切地说,我们应该改变花括号的格式.如果是try/catch或控制结构,我们应该将它改为同一行,如果它是函数/方法/类,它应该在下一行.我对sed和awk知之甚少,它可以很容易地完成这个任务.我也知道这可以用eclipse完成.
好吧,我手上有空闲时间,所以我决定重温我过去的好日子:
在阅读了一些关于awk和sed的内容之后,我决定使用它们可能会更好,因为在awk中添加缩进并在sed中解析字符串更容易.
这是格式化源文件的〜/ sed_script:
# delete indentation
s/^ \+//g
# format lines with class
s/^\(.\+class.\+\) *\({.*\)$/\1\n\2/g
# format lines with methods
s/^\(public\|private\)\( \+static\)\?\( \+void\)\? \+\(.\+(.*)\) *\({.*\)$/\1\2\3 \4\n\5/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
它远非正确的格式化工具,但我希望它可以作为参考示例脚本正常:]祝你学习顺利.