我有一个结构:
我想从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
答案 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