Shell
匹配多個單詞以替換模式
我有一個文件,其中包含類似的數據
.spec.nodes.brokers.runtime.properties.broker.http.numConnections=15 .spec.nodes.clients.runtime.properties.broker.http.numConnections=17 .spec.nodes.servers.runtime.properties.broker.http.numConnections=19
我想替換
runtime.properties
為'"runtime.properties"'
. 我可以手動執行多個 sed,但我想看看是否可以使用模式匹配通過一個 sed 完成它。此外,我不能直接 sed 並替換“runtime.properties”,因為還有其他模式可能與此關鍵字匹配。我需要匹配的東西
.spec.nodes.<one of brokers, clients or servers>,
然後替換
.spec.nodes
應該只在行首,而不是字元串中的任何地方。
給定
$ cat file .spec.nodes.brokers.runtime.properties.broker.http.numConnections=15 .spec.nodes.foo.runtime.properties.broker.http.numConnections=17 .spec.nodes.clients.runtime.properties.broker.http.numConnections=17 .spec.nodes.bar.runtime.properties.broker.http.numConnections=17 .spec.nodes.servers.runtime.properties.broker.http.numConnections=19
然後
$ sed -E "/\.spec\.nodes\.(brokers|clients|servers)/s/runtime\.properties/'\"&\"'/" file .spec.nodes.brokers.'"runtime.properties"'.broker.http.numConnections=15 .spec.nodes.foo.runtime.properties.broker.http.numConnections=17 .spec.nodes.clients.'"runtime.properties"'.broker.http.numConnections=17 .spec.nodes.bar.runtime.properties.broker.http.numConnections=17 .spec.nodes.servers.'"runtime.properties"'.broker.http.numConnections=19
或者
$ sed -E '/\.spec\.nodes\.(brokers|clients|servers)/s/runtime\.properties/'\''"&"'\''/' file .spec.nodes.brokers.'"runtime.properties"'.broker.http.numConnections=15 .spec.nodes.foo.runtime.properties.broker.http.numConnections=17 .spec.nodes.clients.'"runtime.properties"'.broker.http.numConnections=17 .spec.nodes.bar.runtime.properties.broker.http.numConnections=17 .spec.nodes.servers.'"runtime.properties"'.broker.http.numConnections=19