一个衬垫到typedef c结构

use*_*402 2 regex perl sed

我有一个用例,我试图在各种头文件中键入一组结构

例如,我想转换这个:

struct Foo_t
{
   uint8_t one
   uint8_t two;
   uint8_t three;
};
Run Code Online (Sandbox Code Playgroud)

对此:

typedef struct
{
   uint8_t one
   uint8_t two;
   uint8_t three;
} Foo_t;
Run Code Online (Sandbox Code Playgroud)

在高级别,我想使用sed,awk或perl等实用程序来:

  1. 查找以"struct"开头的所有行
  2. 请记住以下示例中的struct标记,Foo_t
  3. 找到第一个大括号"{"
  4. 跳过新行,直到第一次出现结束括号"}"
  5. 插入struct标签(Foo_t)或调用特定stuct的任何内容
  6. 插入分号以结束结构定义

不幸的是,我得到的最远的是以下内容:

find . -regextype egrep -path ./dont_touch -prune -o -name "*.h" -print0 | xargs -0 sed -i 's/struct* /typedef struct /g;'
Run Code Online (Sandbox Code Playgroud)

这种方法显然不起作用,但它至少是我建立起点的起点.

任何帮助将不胜感激.

谢谢!

更新:

测试数据的一个例子是:

test.h

struct Foo_t
{
   uint8_t one;
   uint8_t two;
   uint8_t three;
   uint8_t four;
};

struct Bar_t
{
   float_t one;
   float_t two;
};

struct Baz_t {
   float_t one;
   float_t two;
};
Run Code Online (Sandbox Code Playgroud)

Cor*_*ion 6

假设结构定义中的文本既不包含{nor },则以下Perl oneliner会将所有struct声明转换为typedef声明:

perl -0777 -pi -e 's!\bstruct\b\s+(\w+)\s*(\{.*?\})!typedef struct\n$2 $1!sg' 
Run Code Online (Sandbox Code Playgroud)

-0777 - 将文件作为一个整体插入 $_

-pi - 就地编辑文件

-e - 使用此Perl代码

s!\bstruct\b\s+(\w+)\s*(\{.*?\})!typedef struct\n$2 $1!sg
Run Code Online (Sandbox Code Playgroud)

替换所有struct后跟一个C标识符,然后是{... }by typedef struct,然后是大括号和东西,然后是标识符.有关详细信息,请参阅regex101.

也可以看看

perlre - 用于解释正则表达式部分

perlrun - 用于命令行开关