如何将跨多行的typedef合并为单行?

2024-04-24 23:33:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我想使用bash命令或python将分布在多行上的typedef合并成一行。因为我对脚本完全陌生,我需要你的帮助。

下面是示例输入和预期输出。

输入:

#include <iostream>
#include <list>
#include <map>

using namespace std;

#define MIN_LEN 10
#define MAX_LEN 100

typedef list<int> IntList;

typedef 
map<int, string>
Names;

typedef Record
{
    int id;
    string name;
} MyRecord;

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

输出:

^{pr2}$

Tags: name命令脚本bash示例mapstringlen
1条回答
网友
1楼 · 发布于 2024-04-24 23:33:00

你可以用sed做,但有点复杂。

/^typedef/ {    # If a line starts with 'typedef'
    /;$/! {     # If the line does not end with ';'
        :loop   # Label to branch to
        N       # Append next line to pattern space
        /;$/ {                      # If the pattern space ends with ';'
            /{[^}]*}\|^[^{]*$/ {    # If matching braces or no braces at all
                s/\n/ /g            # Replace all newlines with spaces
                s/  */ /g           # Replace multiple spaces with single spaces
                b                   # Branch to end of cycle
            }
        }
        b loop  # Branch to label
    }
}

第一种情况很简单:

^{pr2}$

这可以通过添加下一行直到找到;来解决,然后用空格替换新行,完成。

但是,包含更多分号的大括号使它更加困难:如果一行以分号结尾,则只有当我们已经看到一对匹配的大括号或根本没有大括号(这是第一种情况)时,语句才会结束。

将脚本(可能没有注释,一些sed不喜欢它们)存储在sedscr中,输入文件的结果如下所示:

$ sed -f sedscr infile
#include <iostream>
#include <list>
#include <map>

using namespace std;

#define MIN_LEN 10
#define MAX_LEN 100

typedef list<int> IntList;

typedef map<int, string> Names;

typedef Record { int id; string name; } MyRecord;

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

这个可以写成一行行,但可能不应该是:

^{4}$

这适用于gnused;BSD sed可能需要更多分号,尤其是在右大括号之前。

相关问题 更多 >