一种用于typedef c结构的衬里

时间:2019-01-04 18:58:12

标签: regex perl sed

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

例如,我要转换它:

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

对此:

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

在较高的层次上,我想使用诸如sed,awk或perl之类的实用程序:

  1. 找到所有以“ struct”开头的行
  2. 记住上面的示例中的struct标记Foo_t
  3. 找到第一个大括号“ {”
  4. 跳过n行,直到第一次出现右括号 “}”
  5. 插入struct标记(Foo_t)或任何特定的结构 叫
  6. 插入分号以结束结构定义

不幸的是,我所得到的最远的是:

find . -regextype egrep -path ./dont_touch -prune -o -name "*.h" -print0 | xargs -0 sed -i 's/struct* /typedef struct /g;'

这种方法显然行不通,但这至少是我赖以建立的起点。

任何帮助将不胜感激。

谢谢!

更新

测试数据的示例为:

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;
};

1 个答案:

答案 0 :(得分:6)

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

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

-0777-将文件整体粘贴到$_

-pi-就地编辑文件

-e-使用此Perl代码

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

将所有struct后面跟一个C标识符,然后用{替换} ... typedef struct,然后是大括号和填充物,然后替换标识符。有关详细信息,请参见regex101

另请参见

perlre-有关正则表达式部分的说明

perlrun-用于命令行开关