Text 匹配后插入一行

Text 匹配后插入一行,text,ansible,Text,Ansible,我试图在最后一次匹配正则表达式后在文件中插入一行。 它实际上是在文件末尾添加行 tasks: - name: add to ansible hosts file lineinfile: dest: "hosts" insertafter: '^\[ansible_ssh_host\]' line: " test ansible_ssh_host=172.0.0.3" 我希望它添加到包含“ansible\u ssh\u host”的最后一行之后

我试图在最后一次匹配正则表达式后在文件中插入一行。 它实际上是在文件末尾添加行

  tasks:
  - name: add to ansible hosts file
    lineinfile:
      dest: "hosts"
      insertafter: '^\[ansible_ssh_host\]'
      line: " test ansible_ssh_host=172.0.0.3"
我希望它添加到包含“ansible\u ssh\u host”的最后一行之后

目标文件

ansible-server ansible_ssh_host=172.0.0.1
template-server ansible_ssh_host=172.0.0.2

[tag_ansible-servers]
ansible-server

[tag_template-servers]
template-server   

“^\[ansible\u ssh\u hosts\]”
表示搜索以
[ansible\u ssh\u hosts]开头的行。
没有一行不是以它开头的

试试这个:

- name: add to ansible hosts file
  lineinfile:
    dest: "hosts"
    insertafter: 'ansible_ssh_host='
    line: " test ansible_ssh_host=172.0.0.3"