[英]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. 在
[...]
可能包含任何数字或字母。
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 }'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.