我想替换与特定模式/行相关联的单词

问题描述

一个文件(socket.cfg)有以下内容

socket1:a:1.2.3.4:wso,ws1,ws2
socket2:b:2.5.6.7:ws3,ws5,ws7

现在我只想更改行中包含“socket1”的 IP,其余部分应保持不变。给我的数据只有socket1和IP要改。

我确实尝试过 lineinfile 并替换模块,但整个模式发生了变化。请帮帮我。 它类似于像这样的 sed 命令 sed /socket1/<Ip_pattern>/<replacing_IP> 所以这会转到 socket1 行选择 IP 并仅替换它。我想要这样的东西。

解决方法

这是你需要的,

- name: replace the ip address
  lineinfile:
    path: /path/to/socket.cfg
    regexp: ^(socket1)(.*)(\d+.\d+.\d+.\d+)(.*)
    line: \g<1>\g<2>{{ inventory_hostname }}\g<4>
    backrefs: yes

注意:我在替换内容时使用了正则表达式组。

我已经用 inventory_hostname 替换了 IP,在我的情况下它是 localhost,您可以将其更新为您想要的任何内容。

输入:

socket1:b:1.2.3.4:ws3,ws5,ws7
socket2:b:2.5.6.7:ws3,ws7

输出:

socket1:b:localhost:ws3,ws7