使用正则表达式递归删除Ansible文件

时间:2019-01-30 13:14:04

标签: regex shell ansible

我有一个结构:

  • dir1
    • subdir1
      • fileX_001.dat
      • fileX_2001.dat
      • fileX_002.dat
      • fileX_2002.dat
      • 文件Y_001.dat
      • fileY_2001.dat
      • ...
    • subdir2
      • fileX_001.dat
      • fileX_2001.dat
      • fileX_002.dat
      • fileX_2002.dat
    • ...

我想从dir1中递归删除所有与正则表达式匹配的文件:.*?_(?!2)[0-9]{2,}\.(dat|DAT)(开头的任何内容,不后跟2,后跟至少2位数字,并以.dat / .DAT结尾)。应该匹配并删除的文件为粗体。

我尝试过:

- name: delete files
  shell: 'ls -R | grep -P ".*?_(?!2)[0-9]{2,}\.(dat|DAT)" | xargs -d"\n" rm'
  args:
    chdir: 'dir1'

但是失败了(rm在目录中找不到文件)。

我也尝试过:

file_regex: '.*?_(?!2)[0-9]{2,}\.(dat|DAT)'

- name: find files
  find:
    paths: "dir1"
    patterns: "{{ file_regex }}"
    use_regex: yes
    recurse: yes
  register: found_files

- name: delete files
  file:
    path: '{{ item.path }}'
    state: absent
  with_items: '{{ found_files.files }}'

,但似乎找不到文件。输出为:

13:15:30 TASK [myrole : find files]
...
13:15:30 Wednesday 30 January 2019  14:15:30 +0200 (0:00:01.008)       0:00:40.241 *****
13:15:30 ok: [xxx.xxx.xxx.xxx.xxx] => {"changed": false, "examined": 483, "files": [], "matched": 0, "msg": ""}
13:15:30 
13:15:30 TASK [myrole : delete files]
...
13:15:30 Wednesday 30 January 2019  14:15:30 +0200 (0:00:00.350)       0:00:40.592 ***** 
13:15:30 

1 个答案:

答案 0 :(得分:1)

patterns参数为list类型。如果Ansible检测到字符串,则使用逗号作为分隔符将其转换为列表。因此,您最终得到两种模式:

        "patterns": [
            ".*?_(?!2)[0-9]{2",
            "}\\.(dat|DAT)"
        ],

要克服这一点,请将您的模式作为列表传递:

- name: find files
  find:
    paths: "dir1"
    patterns:
      - "{{ file_regex }}"
    use_regex: yes
    recurse: yes
  register: found_files