使用 sed 检测和连接多行结构
因此,考虑到我在一段代码中有某种类型的数据结构:
struct apple {
int type, color;
Apple app;
};
// ... more code
我想获取完整的结构定义(以及文件中的任何其他结构定义)并将它们压缩成一行(因此文件产品看起来像像
struct apple { int type, color; Apple app; };
:)。
这是家庭作业的一部分。大约一周前,我刚刚在讲座中学习了 sed,我非常不确定如何做这样的事情。因此,如果您对直接回答问题感到不舒服,如果您能为我指出正确的方向,以便我能够学习如何正确使用此实用程序,我将不胜感激。
我假设可以通过检测结构定义来使用 sed 完成任务,然后继续将每一行读入全局缓冲区,直到找到 } (我假设结构定义中没有联合或任何内容)。不过,这个程序似乎有很多功能,但我找不到任何关于它的精彩介绍。
So, given that I have some type of data structure like this within a segment of code:
struct apple {
int type, color;
Apple app;
};
// ... more code
I want to take the full struct definition (and any other struct definitions in the file) and compress them into one line (so the file product would look something like:
struct apple { int type, color; Apple app; };
).
This is part of a homework assignment. I just learned sed in lecture not a week or so ago, and I'm very unsure as to how to do something like this. As such, if you feel uncomfortable answering things outright, I would appreciate if you could point me in the right direction so that I can learn how to use this utility correctly.
I'm assuming that one could accomplish things with sed by detecting the struct definition, and then keep reading each line into a global buffer until a } is found (I'm assuming there are no unions or anything in the struct definition). There seems to be a lot of power in this program though, and I can't find any great introductions to it.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我会做这样的事情:
构造
/foo/,/bar/
选择模式之间的所有行(包括)。N
命令将换行符和下一行附加到当前模式空间。然后执行著名的 s/// 命令,它将换行符替换为空,即行连接。I'd do something in the line of this:
The construct
/foo/,/bar/
selects all lines (inclusive) between patterns.The
N
command appends a newline and the next line to current pattern space. Then the famouss///
command gets executed which replaces the newline character with nothing, i.e. join of lines.可能有更好的方法来解决这个问题,例如 awk 可能与 tr 一起使用。然而,既然您提到这是家庭作业,并且必须由 sed 完成,我编写了以下命令(一行:D)。注意,有两个“sed”命令。希望能够被接受。
解决问题的命令:
现在让我们做一个测试,我创建了一个名为 tc 的文件查看内容:
现在用 tc 宝贝播放我的 sed 命令:
there may be better way to solve this problem, e.g. awk maybe with tr. However since you mentioned that this is homework, and must be done by sed, I wrote the below commands (one liner :D ). note, there are two "sed" command. hope it could be accepted.
command to solve the problem:
now let's do a test, I created a file named t.c. see the content:
now play my sed commands with the t.c baby: