如何将单行与下一行合并?

时间:2016-02-11 06:51:42

标签: python bash indentation

我工作的代码是混合类型的函数声明。 1)使用旧式的函数声明,即函数名称后面是前一行的函数类型,但不是同一行,2)单个lint中的函数类型和函数名称。

我想更改所有函数声明,以便函数类型和函数名在同一行。

原因: 即使我使用-npsl,gnu“indent”也没有将函数类型放在与函数名称相同的行中。此外,如果函数类型和函数名称之间有新行,那么这些新行也不会被删除。

所以我正在寻找一个简单的bash或python命令,它可以简单地将函数类型与函数名结合起来。一旦完成,我可以使用gnu缩进来缩进休息。

输入:

#include <iostream>
using namespace std;

typedef struct Record
{
    int a;
    string b;
} Record;


void 
putname
(int a, string name)


{
    // do something...
}

float fun1(int integerintegerinteger, float floatfloatfloatfloat,
    double doubledoubledoubledoubledouble, 
char yaroyarogeecheehodahaaluhaneyabaraha,
string illibaribeda

)
{  /* do nothing */ }

Record
fun3() {
    // do something else
}

预期产出:

#include <iostream>

using namespace std;

typedef struct Record
{
    int a;
    string b;
} Record;


void putname (int a, string name)
{
    // do something...
}

float fun1(int integerintegerinteger, float floatfloatfloatfloat, double doubledoubledoubledoubledouble, char yaroyarogeecheehodahaaluhaneyabaraha, string illibaribeda)
{  /* do nothing */ }

Record fun3() 
{
    // do something else
}

是否可以在单个sed或python命令中完成此操作?

1 个答案:

答案 0 :(得分:0)

我能够编写sed命令来完成所提供的工作&#34;功能类型和功能名称之间没有空行&#34;。以下是命令:

/^\(typedef\|using\|namespace\|#\)/ !{  #if line not starts with typedef or using or # or namespace
    /^\s*$/ !{                          #if line not an empty line
        /\(;\|)\|{\|}\)$/ !{            #if line is not ending with ; or ) or { or } 
            N;                          #read next line
            s/\n/ /                     #replace newline with space
        }
    }
}

oneliner:

sed '/^\(typedef\|using\|#\)/ !{/^\s*$/ !{/\(;\|)\|{\|}\)$/ !{N; s/\n/ /}}}' file

请注意,可以采用更有效的方式完成上述工作。因为我是学习者,我找到了上述方法。如果有人可以优化它,那就好了。

最终缩进按以下顺序排列: 1.使用gnu indent缩进代码(由于某种原因,函数类型未与函数名合并) 2.运行sed命令以将函数类型与函数名称合并在一行