Using sed to print between delimiters

余生长醉 提交于 2019-12-13 18:14:34

问题


This is an extension of my previous question recommended by the answerer. Basically, I need sed to print text between delimiters. The delimiters could span multiple lines like:

(abc
d)

Below are sample input and output.

Input

(123) 
aa (a(b)cd)) (g) (c)fff 
abcd(aabb 
d)aa (aeb)oe

correct output

123
a(b  
aabb
d

Note: I only want the text between the first pair of delimiters. If the delimiter spans two lines than I just want the text between first pair that span two lines and move on to the third (next) line. Thus, for the last line in the input I printed 'd' and skip (aeb) and move on to the next line.


回答1:


I used a sed script file (called sedscript) containing:

/^[^(]*([^)]*$/N
s/^[^(]*(\([^)]*\)).*/\1/p

and the command line:

sed -n -f sedscript data

Given the input:

(123)
aa (a(b)cd)) (g) (c)fff
abcd(aabb
d)aa (aeb)oe

It produced the output:

123
a(b
aabb
d

You can do it on a single command line with:

sed -n -e '/^[^(]*([^)]*$/N' -e 's/^[^(]*(\([^)]*\)).*/\1/p' data

The first pattern looks for lines containing an open parenthesis without a close parenthesis after it, and reads the next line into memory and starts over. It repeats that until there is a close parenthesis in the data (or EOF). The second pattern looks for the stuff before an open parenthesis, the open parenthesis, remembers the data from there to the first close parenthesis, followed by the close parenthesis and any other stuff; it replaces that with the remembered string and prints it. Anything else is not printed (-n).



来源:https://stackoverflow.com/questions/6023615/using-sed-to-print-between-delimiters

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