【发布时间】:2019-05-31 08:36:21
【问题描述】:
我有一个用例,我试图在各种头文件中对一组结构进行类型定义
例如,我想转换这个:
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 等实用程序来:
- 查找所有以“struct”开头的行
- 记住后面的结构标签,在上面的例子中,Foo_t
- 找到第一个花括号“{”
- 跳过 n 个新行,直到第一次出现右括号 “}”
- 插入结构标签(Foo_t)或任何特定结构 叫
- 插入分号结束结构定义
不幸的是,我得到的最远的是以下:
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;
};
【问题讨论】:
-
您的
structs 会包含(配对){或}吗?否则,以下应该基本上可以工作:perl -0777 -pi -e 's!\bstruct\b\s+(\w+)\s*(\{.*?\})!typedef struct\n$2 $1!s' *.c(另见regex101 -
@Corion:我做了同样的事情,但我有一个问题。我们如何使用 Perl 或 Python 使用捕获的组。有没有什么方法可以使用 Python 提取上述实现的解决方案?
-
@Deep - 我在上面的 Perl 中使用捕获的组。对于 Python,您可以通过
m = re.search(...); print m.groups(1)访问它们 - 请参阅 Python regex documentation 或将其作为(重复)问题发布