我有一个包含类似数据的文件
.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
只能位于行的开头,而不是字符串中的任何位置。
答案1
给定
$ 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