【问题标题】:Remove every line before a string in file using Ansible使用 Ansible 删除文件中字符串之前的每一行
【发布时间】:2020-02-25 09:03:22
【问题描述】:

我有以下文件:

Scheduled jobs
Locale LANG set to the following: "en"
CONMAN:AWSBHU611W Conman could not initialize the HTTP or HTTPS connection.
Workstation Job Stream SchedTime Job State Pr Start Elapse ReturnCode Dependencies

HCPRODNWA #NW_HC_CA_BKP1 0106 02/13 **************************************** HOLD 10(02/13) (03:22)
NW_HC_CA_PREBKUP1B HOLD 10(02/13)(00:01)
NW_HC_CA_SANREPLICATION HOLD 10(02/13)(00:05)ΩNW_HC_CA_PREBKUP1B
NW_HC_CA_PPBACKUP HOLD 10(02/13)(03:17)
NW_HC_CA_SANREPLICATION
NW_HC_CA_GOLDCOPY HOLD 10(02/13)(00:01)
NW_HC_CA_SANREPLICATION

我想删除以 'Workstation Job...' 开头的行之前的所有行

我的 ansible 代码是:

- name: Extract job details
  replace:
    path: /tmp/tws_jobs
    after: '(^Scheduled)'
    before: '(^Workstation)'
    regexp: '^(.*)$'
    replace: ''

但我无法获得所需的输出。相反,我收到以下消息:

"msg": "Pattern for before/after params did not match the given file: (^Scheduled)(?P<subsection>.*?)(^Workstation)"

【问题讨论】:

  • 我认为问题在于正则表达式中的. 与新行不匹配。也许试试regexp: '(.|\n)*'
  • @Alex,我试过了,但它仍然给出相同的信息

标签: regex ansible regexp-replace ansible-bug


【解决方案1】:

问:“前/后参数的模式与给定文件不匹配...”

A: beforeafter 模式都不匹配文件中的任何行。正确的模式应该是

    after: '^Scheduled(.*)$'
    before: '^Workstation(.*)$'

但是这些模式也不起作用,可能是因为未解决的问题Replace module before/after still broken #47917

可以在一个简化的示例中测试各种模式

shell> cat test.txt
aaa
bbb
ccc
ddd
eee

任务

   - replace:
        path: test.txt
        after: 'bbb'
        before: 'ddd'
        regexp: '^(.*)$'
        replace: ''

按预期工作

shell> cat test.txt
aaa
bbb

ddd
eee

但两者都没有

   - replace:
        path: test.txt
        after: '^bb'
        before: '^dd'
        regexp: '^(.*)$'
        replace: ''

也没有

   - replace:
        path: test.txt
        after: '^bb(.*)$'
        before: '^dd(.*)$'
        regexp: '^(.*)$'
        replace: ''

更改文件中的任何内容

PLAY RECAP *************************************************************************
localhost: ok=1  changed=0  unreachable=0  failed=0  skipped=0  rescued=0  ignored=0

[1]https://github.com/ansible/ansible/issues/47917#issuecomment-686339762

【讨论】:

    【解决方案2】:

    尝试另一种方法:blockinfile

    - name: Extract job details
      blockinfile:
        marker_begin: '^Scheduled'
        marker_end: '^Workstation'
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-11-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-27
      • 2023-03-21
      • 2015-04-09
      相关资源
      最近更新 更多