应该在if语句的同一行,for循环,方法等中打开打开的花括号

时间:2018-02-15 10:54:34

标签: regex shell awk sed powershell-v2.0

假设我有以下代码段:

if(some condition)
{
some code here;
}
else if (some other condition)
{
some more code;
}
public static some_method(something passed here maybe) 
{
some other code;
}

然后它应格式化为:

if(some condition) {
some code here;
} else if (some other condition) {
some more code;
}
public static some_method(something passed here maybe) {
some other code;
}

这只是示例代码。我想为包含“if语句,for循环,方法等”的整个文件运行sed脚本。可能相似或不同的格式。所以大多数脚本的目的应该是将这些开放的花括号移动一行。提前谢谢..

2 个答案:

答案 0 :(得分:1)

#!/bin/bash

# get input filename ...

filename="${1}"

# Do basic checks (etc) ...
if [[ -z "${filename}" ]]
then
    echo "[ERR] No file name supplied."
    echo "Usage: `basename ${0}` \"the file name\""

    exit 1
fi

if [[ ! -f "${filename}" ]]
then
    echo "[ERR] No file named \"${filename}\" exists anywhere."

    exit 1
fi

# Create  "SED crunch script" ...
sedscript="/tmp/sedscript.sed"

cat << EOF > "${sedscript}"

    # if "function syntax found, then read in next line
    # and print, else just print current line ...

    /^.*([^)]*)[ |  ]*$/{

    N

        /^.*([^)]*)[ |  ]*\n[ | ]*{.*$/{

            # Remove newline from first and appended line ...
            s/\n//g

            # ... and print what we have to STDOUT ...
            p

            b skip_default_print
        }

        # Next line did not start with open curly brace,
        # so just print what we currently have and
        # skip default print ..

        p

        b skip_default_print
    }

    p

    :skip_default_print

EOF

# Execute crunch script against code ...
sed -n -f "${sedscript}" "${filename}"

将上述脚本保存到bash脚本中。然后执行如下: (以下示例假定脚本保存为crunch.sh)

./ crunch.sh“code.java”

...其中“code.java”是您希望“紧缩”的代码。结果将发送到STDOUT。

这是我使用的输入:

if(some condition)
{
some code here;
}
else if (some other condition)
{
some more code;
}
public static some_method(something passed here maybe) 
{
some other code;
}

并输出:

if(some condition){
some code here;
}
else if (some other condition){
some more code;
}
public static some_method(something passed here maybe) {
some other code;
}

答案 1 :(得分:1)

重复你从Tom Fenech那里得到的评论,特别是如果要求变得更复杂:

  

我的建议不是自己实现,而是使用   用于您正在编写的语言的现有美化工具

但是,这仍然是一个可能的解决方案,但我不知道它在现实世界中的表现如何。 RS="\n[[:space:]]*{"将输入拆分为在换行符之前换行符后面有空格,制表符等的点,然后将其替换为' {'。保存一行并在以后打印它可以避免在输出结尾添加最终{

awk '
    BEGIN { RS="\n[[:space:]]*{"
    NR == 1 {
        line=$0; 
        next 
    } 
    { 
        printf "%s", line" {"; 
        line=$0 
    } 
    END {
        print line
}' _file_with_code_

或者,可以使用更多awk功能将其写成如下。这会导致文件末尾的{结尾,但已被添加的sed程序删除

awk '
    BEGIN { 
        # break record on `\n{`
        RS="\n[[:space:]]*{";
        # replace with `{`
        ORS=" {" 
    } 
    # print for each line
    { print }
' input_file | 
sed '
    # for last line ($), `substitute` trailing `{` with ``
    $ s/{$//
'