0

Say a file (socket.cfg) has the following

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. The data given to me would be only socket1 and IP to be changed.

I did try lineinfile and replace module but the whole pattern changes. 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. I want something like this.

Kushal
  • 3
  • 1

1 Answers1

1

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.

Input:

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

Output:

socket1:b:localhost:ws3,ws5,ws7
socket2:b:2.5.6.7:ws3,ws5,ws7
Zeitounator
  • 38,476
  • 7
  • 53
  • 66
Shubham Vaishnav
  • 1,637
  • 6
  • 18
  • @Kushal, If you are satisfied with the answer you can mark it as accepted answer, so that it will be helpful for others and it will also close this question. – Shubham Vaishnav Jan 21 '21 at 07:39