简体   繁体   English

使用sed查找被样式包围的文本

[英]Find text enclosed by patterns using sed

I have a config file like this: 我有一个这样的配置文件:

[whatever]
Do I need this? no!

[directive]
This lines I want
Very much text here
So interesting

[otherdirective]
I dont care about this one anymore

Now I want to match the lines in between [directive] and [otherdirective] without matching [directive] or [otherdirective] . 现在,我想匹配[directive][otherdirective]之间的行,而不匹配[directive][otherdirective]

Also if [otherdirective] is not found all lines till the end of file should be returned. 同样,如果未找到[otherdirective] ,则应返回直到文件末尾的所有行。 The [...] might contain any number or letter. [...]可能包含任何数字或字母。

Attempt 尝试

I tried this using sed like this: 我像这样使用sed尝试了这个:

sed -r '/\[directive\]/,/\[[[:alnum:]+\]/!d

The only problem with this attempt is that the first line is [directive] and the last line is [otherdirective] . 这种尝试的唯一问题是第一行是[directive] ,最后一行是[otherdirective]

I know how to pipe this again to truncate the first and last line but is there a sed solution to this? 我知道如何通过管道再次截断第一行和最后一行,但是有sed解决方案吗?

You can use the range, as you were trying, and inside it use // negated. 您可以尝试使用范围,并且在其内部使用//否定。 When it's empty it reuses last regular expression matched, so it will skip both edge lines: 当为空时,它将重用匹配的最后一个正则表达式,因此它将跳过两条边线:

sed -n '/\[directive\]/,/\[otherdirective\]/ { //! p }' infile

It yields: 它产生:

This lines I want
Very much text here
So interesting

Here is a nice way with awk to get section of data. 这是使用awk获取数据部分的一种好方法。

awk -v RS= '/\[directive\]/' file
[directive]
This lines I want
Very much text here
So interesting

When setting RS to nothing RS= it divides the file up in records based on blank line. 将RS设置为空时, RS= ,它将基于空白行将文件分成多个记录。
So when searching for [directive] it will print that record. 因此,当搜索[directive] ,它将打印该记录。
Normally a record is one line, but due to the RS (record selector) is change, it gives the block. 通常,一条记录是一行,但是由于RS(记录选择器)被更改,因此它给出了块。

Okay damn after more tries I found the solution or merely one solution: 好吧,该死,在尝试了更多解决方案之后,我还是找到了一个解决方案:

sed -rn '/\[buildout\]/,/\[[[:alnum:]]+\]/{
    /\[[[:alnum:]]+\]/d
    p }'

is this what you want? 这是你想要的吗?

\[directive\](.*?)\[

Look here 看这里

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM