![](/img/trans.png)
[英]Using sed to find replace in a file but not on lines matching multiple patterns
[英]Find text enclosed by patterns using sed
我有一个这样的配置文件:
[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
现在,我想匹配[directive]
和[otherdirective]
之间的行,而不匹配[directive]
或[otherdirective]
。
同样,如果未找到[otherdirective]
,则应返回直到文件末尾的所有行。 在[...]
可能包含任何数字或字母。
我像这样使用sed
尝试了这个:
sed -r '/\[directive\]/,/\[[[:alnum:]+\]/!d
这种尝试的唯一问题是第一行是[directive]
,最后一行是[otherdirective]
。
我知道如何通过管道再次截断第一行和最后一行,但是有sed
解决方案吗?
您可以尝试使用范围,并且在其内部使用//
否定。 当为空时,它将重用匹配的最后一个正则表达式,因此它将跳过两条边线:
sed -n '/\[directive\]/,/\[otherdirective\]/ { //! p }' infile
它产生:
This lines I want
Very much text here
So interesting
这是使用awk
获取数据部分的一种好方法。
awk -v RS= '/\[directive\]/' file
[directive]
This lines I want
Very much text here
So interesting
将RS设置为空时, RS=
,它将基于空白行将文件分成多个记录。
因此,当搜索[directive]
,它将打印该记录。
通常,一条记录是一行,但是由于RS(记录选择器)被更改,因此它给出了块。
好吧,该死,在尝试了更多解决方案之后,我还是找到了一个解决方案:
sed -rn '/\[buildout\]/,/\[[[:alnum:]]+\]/{
/\[[[:alnum:]]+\]/d
p }'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.