随笔-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
posted @   LiYanbin  阅读(1)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?
· 如何调用 DeepSeek 的自然语言处理 API 接口并集成到在线客服系统
点击右上角即可分享
微信分享提示