gpt4 book ai didi

使用 shell 脚本的 Java 代码格式化

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:04:27 25 4
gpt4 key购买 nike

我知道这很愚蠢,但我无法克服好奇心。是否可以编写一个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 来完成。

最佳答案

好吧,我有一些空闲时间,所以我决定重温我过去的 Linux 时光:]

在阅读了一些关于 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

它远不是合适的格式化工具,但我希望它可以作为示例脚本供引用:]祝你学习顺利。

关于使用 shell 脚本的 Java 代码格式化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1137946/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com