在 ( ) sed 之间打印文本 [英] Print text between ( ) sed
问题描述
这是我之前的问题的延伸.在那个问题中,我需要检索括号之间的文本,其中所有文本都在一行上.现在我有这个案例:
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
针对我的问题可能引起的混淆,让我澄清一下.基本上,我需要在可能跨越多行的分隔符之间打印文本.
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
现在我想让 Sed 挑选出分隔符("和)"之间的文本.所以输出将是:
Now I want Sed to pick out text between the delimiter "(" and ")". So the output would be:
1234
567
abc
请注意,左右括号不在同一行上,但它们仍算作 1234 567 的分隔符,因此我需要打印该部分文本.(注意,我只想要第一对分隔符之间的文本).
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).
任何帮助将不胜感激.
推荐答案
啊!另一个棘手的 sed 难题 :)
Ah! another tricky sed puzzle :)
我相信这段代码可以解决您的问题:
I believe this code will work for your problem:
sed -n '/(/,/)/{:a; $!N; /)/!{$!ba}; s/.*(\([^)]*\)).*/\1/p}' file
输出
对于它提供的输入:
OUTPUT
For the provided input it produced:
1234
567
abc
说明:
-n
抑制常规 sed 输出/(/,/)/
用于(
和)
之间的范围选择:a
用于标记标签 a$!N
表示将输入的下一行追加到当前模式空间中/)/!
表示如果)
在当前模式空间中不匹配,则执行某些操作/)/!${!ba}
表示如果)
在当前模式空间中不匹配,则转到标签a
s/.*(\([^)]*\)).*/\1/
表示替换(
和)之间的内容代码> 只是内容,从而去掉括号
\1
用于第 1 组的反向引用,即\(
和\)
之间的文本p
用于打印替换内容
-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
这篇关于在 ( ) sed 之间打印文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!