使用 sed 在分隔符之间打印 [英] Using sed to print between delimiters

查看:59
本文介绍了使用 sed 在分隔符之间打印的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我之前的问题的延伸 回答者推荐.基本上,我需要 sed 在分隔符之间打印文本.分隔符可以跨越多行,如:

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.

输入

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

正确输出

123
a(b  
aabb
d

注意:我只想要第一对分隔符之间的文本.如果分隔符跨越两行,我只想要跨越两行的第一对之间的文本并移至第三(下)行.因此,对于输入的最后一行,我打印了 'd' 并跳过 (aeb) 并移至下一行.

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.

推荐答案

我使用了一个 sed 脚本文件(称为 sedscript),其中包含:

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

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

和命令行:

sed -n -f sedscript data

给定输入:

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

它产生了输出:

123
a(b
aabb
d

您可以在单个命令行上使用:

You can do it on a single command line with:

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

第一个模式查找包含左括号而后没有右括号的行,并将下一行读入内存并重新开始.它重复,直到数据(或 EOF)中有一个右括号.第二个模式查找左括号之前的内容,左括号,记住从那里到第一个右括号的数据,然后是右括号和任何其他内容;它用记住的字符串替换它并打印它.不打印其他任何内容 (-n).

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

这篇关于使用 sed 在分隔符之间打印的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆