如何删除Ansible中匹配项之间的空行

问题描述 投票:2回答:2

我试图使用Ansible删除两行之间的空行但无法使其工作。我的源文件如下所示:

###This line has blank lines after it



###End of block

#More lines

我希望结果看起来像这样:

###This line has blank lines after it
###End of block

#More lines

到目前为止,我使用替换模块执行此任务:

- name: Remove blank lines between matches
  replace:
    path: /home/vagrant/abcd
    after: '###This line has blank lines after it'
    regexp: '(^\n)'
    replace: ''
    before: '###End of block'

但这项任务似乎不起作用。实际上,该任务对源文件没有任何作用。

如果我删除任务的最后一行(之前:'### End of block')。线条确实被删除,但它也删除所有空行,直到EOF不是我想要的。以下是删除最后一行的结果:

###This line has blank lines after it###End of block
#More lines

这不是预期的。

我有一个使用sed的解决方案,但我想尽可能保持其幂等性。也许我需要更好的正则表达式?

有什么想法吗?

谢谢。

ansible
2个回答
1
投票

根据这个问题:https://github.com/ansible/ansible/issues/31354在参数之后和之前一起使用目前不能按预期工作。

您可以从任务中删除参数,在这种情况下它将按预期工作,但我知道这不是您想要实现的。


1
投票

在玩了这个以及使用正则表达式后,我想出了这个:

- name: Remove blank lines between matches
  replace:
    path: /home/vagrant/abcd
    after: '###This line has blank lines after it'
    regexp: '(^\s*$)'
    replace: ''

这会产生:

###This line has blank lines after it
###End of block

#More lines

这就是我追求的目标。但是我会等到bug被修复后再用于生产。

© www.soinside.com 2019 - 2024. All rights reserved.