[英]I want to replace a word which is associated with a particular pattern/line
Say a file (socket.cfg) has the following假设一个文件(socket.cfg)具有以下内容
socket1:a:1.2.3.4:wso,ws1,ws2
socket2:b:2.5.6.7:ws3,ws5,ws7
Now I want to change only the IP where "socket1" contains in the line and the rest should remain the same.现在我只想更改“socket1”包含在行中的 IP 并且 rest 应该保持不变。 The data given to me would be only socket1 and IP to be changed.
给我的数据只有 socket1 和 IP 需要更改。
I did try lineinfile and replace module but the whole pattern changes.我确实尝试过 lineinfile 并替换模块,但整个模式发生了变化。 Kindly help me out.
请帮帮我。 It is similar to the sed command like this
sed /socket1/<Ip_pattern>/<replacing_IP>
So this goes to socket1 line picks the IP and replaces only that.它类似于 sed 命令,例如
sed /socket1/<Ip_pattern>/<replacing_IP>
所以这转到 socket1 行,只选择 ZA12A3079E14CED46E69BA52B8A90B。 I want something like this.我想要这样的东西。
Here is what you need,这里是你需要的,
- 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
Note: I have used regex groups while replacing the contents.注意:我在替换内容时使用了正则表达式组。
I have replaced the IP with the inventory_hostname
which is localhost in my case, you can update it to whatever you want.我已将 IP 替换为
inventory_hostname
,在我的例子中是localhost,您可以将其更新为您想要的任何内容。
Input:输入:
socket1:b:1.2.3.4:ws3,ws5,ws7
socket2:b:2.5.6.7:ws3,ws5,ws7
Output: Output:
socket1:b:localhost:ws3,ws5,ws7
socket2:b:2.5.6.7:ws3,ws5,ws7
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.