[英]Use sed to replace string - only after pattern match
我有以下XML:
<xml>
<bean id="bean1"
class="class1"
singleton="false">
<property name="dbPoolName" value="pool"/>
<property name="dirName" value="myDir"/>
<!-- <property name="MyProperty" value="5000"/> -->
</bean>
<bean id="bean2"
class="class2"
singleton="false">
<property name="dbPoolName" value="pool"/>
<property name="dirName" value="myDir"/>
<!-- <property name="MyProperty" value="5000"/> -->
</bean>
<bean id="bean3"
class="class3"
singleton="false">
<property name="dbPoolName" value="pool"/>
<property name="dirName" value="myDir"/>
<!-- <property name="MyProperty" value="5000"/> -->
</bean>
</xml>
我需要取消注釋元素:
<!-- <property name="MyProperty" value="5000"/> -->
僅在ID為“ bean3”的bean內部。 然后,我需要修改其值,以使其為50而不是5000。
我嘗試使用以下命令:
grep -A 4 "bean3" file.xml | sed 's/<!--//' | sed 's/-->//' | sed 's/5000/50/'
但是我無法在文件中替換它。
我應該使用sed和/或grep嗎?
如果您使用的是GNU sed,則可以使用一個命令完成所有操作:
sed '/bean3/,+5s/<!-- *\|-->//g; /bean3/,+5s/5000/50/' file.xml
您只需要運行sed
命令的一個實例。 單個sed命令用分號分隔;
。 在這種情況下,我們只需要兩個sed命令:
\\|
替換<!--
(可選后跟空格)和-->
為空字符串\\|
運算符和g
(全局)修飾符。 5000
與50
。 /bean3/,+5
范圍是GNU擴展; 這樣可以確保僅在首次出現bean3
之后的5行上執行上述替換。 該范圍用於兩個替換命令。
如果您確信sed命令可以執行所需的操作,則可以使用-i
/ --in-place
選項更改file.xml
。
這是一個AWK腳本,它掃描id="bean3"
的bean
標簽並取消注釋,並將"5000"
更改為"50"
直到下一個bean
標簽為止:
#!/usr/bin/awk
BEGIN{ in_bean3 = 0 }
$0~/<bean / { # match start of bean tag
if ( $0 ~ "id=\"bean3\"" ) {
# Set flag for desired context
in_bean3 = 1
print
next
} else { # clear flag
in_bean3 = 0
}
}
in_bean3 { # in desired context
sub(/<!-- */, "")
sub(/ *-->/, "")
sub(/"5000"/, "\"50\"")
}
1
請注意,最后的1
執行打印行的默認操作。
$ awk '/<bean id=/{f=(/bean3/?1:0)} f&&gsub(/<!-- *| *-->/,""){sub(/00/,"")} 1' file
<xml>
<bean id="bean1"
class="class1"
singleton="false">
<property name="dbPoolName" value="pool"/>
<property name="dirName" value="myDir"/>
<!-- <property name="MyProperty" value="5000"/> -->
</bean>
<bean id="bean2"
class="class2"
singleton="false">
<property name="dbPoolName" value="pool"/>
<property name="dirName" value="myDir"/>
<!-- <property name="MyProperty" value="5000"/> -->
</bean>
<bean id="bean3"
class="class3"
singleton="false">
<property name="dbPoolName" value="pool"/>
<property name="dirName" value="myDir"/>
<property name="MyProperty" value="50"/>
</bean>
</xml>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.