打印 ( ) 之间的文本 sed
这是我之前的问题的扩展。在这个问题中,我需要检索括号之间的文本,其中所有文本都在一行上。现在我有这种情况:
(aop)
(abc
d)
这次,左括号可以在一行上,右括号可以在另一行上,所以:
(abc
d)
也算作分隔符 '( )
' 之间的文本,我需要打印它作为
abc
d
编辑: 针对我的问题可能存在的混乱,让我澄清一下。基本上,我需要在可能跨越多行的分隔符之间打印文本。
例如,我的文件中有以下文本:
randomtext(1234
567) randomtext
randomtext(abc)randomtext
现在我希望 Sed 挑选出分隔符“(”和“)”之间的文本。所以输出将是:
1234
567
abc
请注意,左括号和右括号不在同一行,但它们仍然算作 1234 567 的分隔符,因此我需要打印文本的该部分。 (注意,我只想要第一对分隔符之间的文本)。
任何帮助将不胜感激。
This is an extension of my previous question. In that question, I needed to retrieve the text between parentheses where all the text was on a single line. Now I have this case:
(aop)
(abc
d)
This time, the open parenthesis can be on one line and the close parenthesis on another line, so:
(abc
d)
also counts as text between the delimiters '( )
' and I need to print it as
abc
d
EDIT:
In response to possible confusions of my question, let me clarify a little. Basically, I need to print text between delimiters which could span multiple lines.
for example I have this text in my file:
randomtext(1234
567) randomtext
randomtext(abc)randomtext
Now I want Sed to pick out text between the delimiter "(" and ")". So the output would be:
1234
567
abc
Notice that the left and right brackets are not on the same line but they still count as a delimiter for 1234 567, so I need to print that part of the text. (note, I only want the text between the first pair of delimiters).
Any help would be appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
啊!另一个棘手的 sed 难题:)
我相信这段代码可以解决您的问题:
输出
对于它生成的提供的输入:
解释:
-n
抑制常规 sed 输出/(/,/)/
用于在(
和)
之间进行范围选择:a
用于将标签标记为$!N
表示将下一行输入追加到当前模式空间/)/!
表示如果)
在当前模式中不匹配,则执行一些操作spacea
/)/!${!ba}
表示如果)
在当前模式空间s/ .*(\([^)]*\)).*/\1/
表示仅将(
和)
之间的内容替换为剥离的内容括号外的\1
用于组 1 的反向引用,即\(
和\)
之间的文本p
用于打印替换的内容Ah! another tricky sed puzzle :)
I believe this code will work for your problem:
OUTPUT
For the provided input it produced:
Explanation:
-n
suppresses the regular sed output/(/,/)/
is for range selection between(
and)
:a
is for marking a label a$!N
means append the next line of input into the current pattern space/)/!
means do some actions if)
is not matched in current pattern space/)/!${!ba}
means go to labela
if)
is not matched in current pattern spaces/.*(\([^)]*\)).*/\1/
means replace content between(
and)
by just the content thus stripping out parenthesis\1
is for back reference of group 1 i.e. text between\(
and\)
p
is for printing the replaced content此链接有答案。我解释一下以满足您的需求:
This link has the answer. I am paraphrasing to match your need:
给出的答案对我的情况不起作用。对我有用的是:
^^^
这通过删除换行符将整个文件放在一行中。
然后我进一步将其输入答案 这里。 (注意:该问题中使用的是 OPEN 和 CLOSE,而不是括号)
The answer given didn't work for my case. What worked for me was:
^^^
this puts the whole file in a single line by deleting line breaks.
and then I further piped it into the answer here. (note: instead of brackets, OPEN and CLOSE are used in that question)