Print text between ( ) sed

爱⌒轻易说出口 提交于 2019-12-19 11:39:21

问题


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.


回答1:


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

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 label a if ) is not matched in current pattern space
  • s/.*(\([^)]*\)).*/\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



回答2:


This link has the answer. I am paraphrasing to match your need:

sed -n '1h;1!H;${;g;s/.*(\([^)]*\)).*/\1/;p}' < your_input



回答3:


The answer given didn't work for my case. What worked for me was:

cat file | tr -d '\n'

^^^ 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)



来源:https://stackoverflow.com/questions/5972908/print-text-between-sed

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!