[英]Ansible delete files recursively with regex
I have a structure:我有一个结构:
From the dir1, I want to delete recursively all the files that matches regular expression: .*?_(?!2)[0-9]{2,}\\.(dat|DAT)
(anything at the beginning, not followed by 2, followed by at least 2 digits and ended by .dat/.DAT).从 dir1,我想递归删除所有匹配正则表达式的文件:
.*?_(?!2)[0-9]{2,}\\.(dat|DAT)
(任何开头,不遵循由 2,后跟至少 2 位数字并以 .dat/.DAT 结尾)。 The files that should match and be deleted are bold.应该匹配并被删除的文件是粗体的。
I tried:我试过:
- name: delete files
shell: 'ls -R | grep -P ".*?_(?!2)[0-9]{2,}\.(dat|DAT)" | xargs -d"\n" rm'
args:
chdir: 'dir1'
but it failed ( rm
could not find files in the directory).但它失败了(
rm
在目录中找不到文件)。
I also tried:我也试过:
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 }}'
but seems like no file is found.但似乎没有找到文件。 The output is:
输出是:
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
patterns
argument is of list
type. patterns
参数是list
类型。 If Ansible detects a string, it is converted to list using comma as separator.如果 Ansible 检测到一个字符串,它将使用逗号作为分隔符将其转换为列表。 So you end up with two patterns:
所以你最终得到两种模式:
"patterns": [
".*?_(?!2)[0-9]{2",
"}\\.(dat|DAT)"
],
To overcome this, pass your pattern as a list:为了克服这个问题,请将您的模式作为列表传递:
- name: find files
find:
paths: "dir1"
patterns:
- "{{ file_regex }}"
use_regex: yes
recurse: yes
register: found_files
As we noticed there are some challenges with regex, delete and copy module.正如我们注意到的,正则表达式、删除和复制模块存在一些挑战。 So we can try with shell or command module as given.
所以我们可以尝试使用给定的 shell 或命令模块。
- name: Delete all tar files from /var/log/
become: true
command_warnings=false
command: "rm -f /var/log/*.tar”
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.