![](/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.