3

我在长 c 文件中有一个结构块

struct node {
   int val;
   struct node *next;
};

如何使用 sed 函数找到这个结构块并将其转换为一行。所以它看起来像这样:

struct node {   int val;   struct node *next;};

提前致谢


我的输入是这样的:

struct node {
   int val;
   struct node *next;
};

typedef struct {
   int numer;
   int denom;
} Rational;

int main()
{
struct node head;
Rational half, *newf = malloc(sizeof(Rational));

head = (struct node){ 5, NULL };
half = (Rational){ 1, 2 };
*newf = (Rational){ 2, 3 };
}

我的输出是:

struct node { int val; struct node *next;};

typedef struct { int numer; int denom;} Rational;int main(){struct node head;Rational  half, *newf = malloc(sizeof(Rational));head = (struct node){ 5, NULL };
half = (Rational){ 1, 2 };
*newf = (Rational){ 2, 3 };
}

我只希望 struct node:struct node { int val; struct node *next;};
和 typedef struct:typedef struct { int numer; int denom;} Rational; 在一行中。然而 int main() 被附加到 Rational 的末尾;

我希望 main 函数中的内容保持原样。

4

1 回答 1

3

使用 sed:

sed '/struct[^(){]*{/{:l N;s/\n//;/}[^}]*;/!t l;s/  */ /g}' input.c

sed看到一个结构定义 ( /struct[^{]*{/) 时,它将读取行,直到};在一行 ( :l N;s/\n//;/[}];/!t l;) 上看到 a ,同时还删除换行符。当它匹配时,};它会删除多余的空格 ( ;s/ */ /g)。

于 2012-09-19T20:01:00.847 回答