grep 从第一个单词周围的行中查找第二个单词
我有一个这样的文件:
ABC1 对象类型 ... ... 键 {XYZ1} ... ... ABC2 对象类型 ... ... ABC3 对象类型 ... ... 键 { XYZ3 } ... ...
我的第一个搜索词是 KEY(因为它在文件中出现较少),第二个搜索词是 OBJECT-TYPE。 OBJECT-TYPE 可以出现在 KEY 行上方几行(可能是 5 或 10 行)。如果在文件中找到键,我需要具有键值和相应对象类型值的输出。
完全就像:
ABC1 KEY1
ABC2 KEY2
I have a file like this:
ABC1 OBJECT-TYPE ... ... KEY { XYZ1 } ... ... ABC2 OBJECT-TYPE ... ... ABC3 OBJECT-TYPE ... ... KEY { XYZ3 } ... ...
My first search word is KEY (as its occurs less in a file) and second search word is OBJECT-TYPE. OBJECT-TYPE can occur few lines (may be 5 or 10) above the line with KEY. If a KEY is found in a file, I need output that has the key-value and corresponding object-type-value.
Exactly like:
ABC1 KEY1
ABC2 KEY2
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
假设您想要所有对象的所有键,并且键列在对象下面,您可以这样做:
输出:
如果您只想要每个对象树中第一个对象的键,其中对象树由一个空行你应该尝试这个:
输出:
Assuming that you want all keys for all objects, and keys are listed below objects, this is how you might do it:
output:
In case you only want the keys of the first object in each tree of objects, where object trees are separated by an empty line you should try this:
output:
很难说出你真正想做什么。
It's hard to tell what you're really trying to do.
以下内容可能很接近。它适用于给定的输入,但它做出了我不知道是否正确的假设。例如,它假设大括号和键值之间有空格。
The following may be close. It works for the given input, but it makes assumptions that I do not know are true. For example, it assumes that the curly brackets have spaces between them and the key value.
向后迭代文件,找到 KEY 以及该键后面的所有对象类型可能会更容易。
鉴于上面的示例,此输出
如果您需要输出以与原始文件相同的顺序出现,请将
|tac
添加到管道。It might be easier to iterate through the file backwards, find the KEY and the all the Object-Types following the key.
Given your example above, this outputs
If you need the output to appear in the same order as the original file, add
|tac
to the pipeline.