随笔-shell-文本替换
有一文件内容如下
filebeat.inputs:
...
multiline.match: after
fields_under_root: true
scan_frequency: 5s
fields:
xxxxxxxxx: mmmmmmmmmmmmmmmmu
localhost: 99.99.99.99
filebeat.config.modules:
path: ${path.config}/modules.d/*.yml
reload.enabled: false
把 localhost 后面的值99.99.99.99 替换成想要的值。要考虑可能有多处localhost:
sed '/.*fields.*/{:1;n;/^\s*localhost:/!b1;s/:.*/: 192.168.78.165/}' 1.txt
xip=192.168.78.165;sed '/.*fields.*/{:1;n;/^\s*localhost:/!b1;s/:.*/: '${xip}'/}' 1.txt
:1 标签
n 读取下一行
/^\s*localhost:/!b1 匹配到行后不跳转到标签1
s/:.*/: 192.168.78.165/ 将:和:后面的字符替换为: 192.168.78.165
+++
参考:http://bbs.chinaunix.net/thread-4156030-1-1.html
点击查看代码
**question**: 怎么匹配到关键字"[server02]"后,搜索余下的行里第一个匹配到"port"的值
因为port位置可能不是固定的,所以不能用下面的方法: sed -i "/\[server02\]/I,+2 s/port.*/port=1111/" filename
-------------------------------------------
[server01]
id=7
ip=192.168.1.1
port=3306
[server02]
ip=192.168.1.2
port=3307
con=10
[server03]
ip=192.168.1.3
maxconn=100
port=3308
别人的回答:
sed '/\[server02\]/{:1;n;/^port=/!b1;s/=.*/=1111/}' file
:1 标签
n 读取下一行
/^port=/!b1 匹配到以port=开头的行不跳转到标签1
s/=.*/=1111/ 将=和=后面的字符替换为=1111
本文来自博客园,作者:LiYanbin,转载请注明原文链接:https://www.cnblogs.com/stellar-liyanbin/p/18637291

浙公网安备 33010602011771号