使用 sed 检测和连接多行结构 [英] Detecting and concatenating a multi-line structure using 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; };
).
这是家庭作业的一部分.大约一周前,我刚刚在讲座中学习了 sed,我非常不确定如何做这样的事情.因此,如果您对直接回答问题感到不舒服,如果您能指出正确的方向,以便我可以学习如何正确使用此实用程序,我将不胜感激.
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.
我假设可以通过检测结构定义来使用 sed 完成任务,然后继续将每一行读入全局缓冲区,直到找到 }(我假设结构定义中没有联合或任何内容).不过这个程序似乎有很大的力量,我找不到任何关于它的精彩介绍.
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.
推荐答案
我会做这样的事情:
$ sed -n '/struct/,/};/p' input | sed -e ':a;N;$!ba;s/\n//g'
struct apple { int type, color; Apple app;};
结构 /foo/,/bar/
选择模式之间的所有行(包括).
The construct /foo/,/bar/
selects all lines (inclusive) between patterns.
N
命令将换行符和下一行附加到当前模式空间.然后执行著名的 s///
命令,该命令将换行符替换为空字符,即行的连接.
The N
command appends a newline and the next line to current pattern space. Then the famous s///
command gets executed which replaces the newline character with nothing, i.e. join of lines.
这篇关于使用 sed 检测和连接多行结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!