简体   繁体   English

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

[英]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.

相关问题 如何使用ansible替换文件中的特定行? - How to replace a particular line in a file using ansible? ansible-替换现有行中的字符串或单词,而不替换所有行 - ansible - replace a string or word in existing line without replace all the line 如何用Ansible Playbook替换具有多个特殊字符的行 - How to replace a line which has multiple special characters with ansible playbook 是否有更好的方法使用Ansible剧本遍历节点计算机上的多个文件并搜索n替换特定行 - Is there a better way to iterate through multiple files on the node machine using Ansible playbook and search n replace a particular line 是否可以使用Ansible playbook迭代节点机器上的多个文件,并搜索n替换特定行 - Is it possible to iterate through multiple files on the node machine using Ansible playbook and search n replace a particular line ansible lineinfile 根据输入数组替换多个文件中包含默认端口模式的行开始 - ansible lineinfile replace a line begin containing a pattern with default ports in multiple files based on input array Ansible:替换文件中的单词 - Ansible: Replace word in file 查找模式并替换 Ansible - Find pattern and replace Ansible 我正在尝试使用 regex_replace 命令提取子字符串。 我想在这里提取“SWIFTInward” - I am trying to extract a substring using regex_replace command . I want to extract “SWIFTInward” here 在正则表达式中使用正则表达式替换单词 - using regexp in ansible to replace word
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM