简体   繁体   中英

I want to replace a word which is associated with a particular pattern/line

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM