使用shell脚本进行Java代码格式化

前端之家收集整理的这篇文章主要介绍了使用shell脚本进行Java代码格式化前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我知道这很傻但我不能克服好奇心.是否可以编写一个 shell脚本来格式化一段 java代码

例如,如果用户代码中写入:

  1. public class Super{
  2. public static void main(String[] args){
  3. System.out.println("Hello world");
  4. int a=0;
  5. if(a==100)
  6. {
  7. System.out.println("Hello world");
  8. }
  9. else
  10. {
  11. System.out.println("Hello world with else");
  12. }
  13. }
  14. }

我想写一个shell脚本,它会使代码像这样.

  1. public class Super
  2. {
  3. public static void main(String[] args)
  4. {
  5. System.out.println("Hello world");
  6. int a=0;
  7. if(a==100){
  8. System.out.println("Hello world");
  9. }
  10. else{
  11. System.out.println("Hello world with else");
  12. }
  13. }

确切地说,我们应该改变花括号的格式.如果是try / catch或控制结构,我们应该将它改为同一行,如果它是函数/方法/类,它应该在下一行.我对sed和awk知之甚少,它可以很容易地完成这个任务.我也知道这可以用eclipse完成.

好吧,我手上有空闲时间,所以我决定重温我过去的好日子:

在阅读了一些关于awk和sed的内容之后,我决定使用它们可能会更好,因为在awk中添加缩进并在sed中解析字符串更容易.

这是格式化源文件的〜/ sed_script:

  1. # delete indentation
  2. s/^ \+//g
  3.  
  4. # format lines with class
  5. s/^\(.\+class.\+\) *\({.*\)$/\1\n\2/g
  6.  
  7. # format lines with methods
  8. s/^\(public\|private\)\( \+static\)\?\( \+void\)\? \+\(.\+(.*)\) *\({.*\)$/\1\2\3 \4\n\5/g
  9.  
  10. # format lines with other structures
  11. /^\(if\|else\|for\|while\|case\|do\|try\)\([^{]*\)$/,+1 { # get lines not containing '{'
  12. # along with the next line
  13. /.*{.*/ d # delete the next line with '{'
  14. s/\([^{]*\)/\1 {/g # and add '{' to the first line
  15. }

这是添加缩进的〜/ awk_script:

  1. BEGIN { depth = 0 }
  2. /}/ { depth = depth - 1 }
  3. {
  4. getPrefix(depth)
  5. print prefix $0
  6. }
  7. /{/ { depth = depth + 1 }
  8.  
  9. function getPrefix(depth) {
  10. prefix = ""
  11. for (i = 0; i < depth; i++) { prefix = prefix " "}
  12. return prefix
  13. }

你就这样使用它们:

  1. > sed -f ~/sed_script ~/file_to_format > ~/.tmp_sed
  2. > awk -f ~/awk_script ~/.tmp_sed

它远非正确的格式化工具,但我希望它可以作为参考示例脚本正常:]祝你学习顺利.

猜你在找的Bash相关文章